]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/cargo_target_spec.rs
Merge #9242
[rust.git] / crates / rust-analyzer / src / cargo_target_spec.rs
1 //! See `CargoTargetSpec`
2
3 use cfg::{CfgAtom, CfgExpr};
4 use ide::{FileId, RunnableKind, TestId};
5 use project_model::{self, TargetKind};
6 use vfs::AbsPathBuf;
7
8 use crate::{global_state::GlobalStateSnapshot, Result};
9
10 /// Abstract representation of Cargo target.
11 ///
12 /// We use it to cook up the set of cli args we need to pass to Cargo to
13 /// build/test/run the target.
14 #[derive(Clone)]
15 pub(crate) struct CargoTargetSpec {
16     pub(crate) workspace_root: AbsPathBuf,
17     pub(crate) cargo_toml: AbsPathBuf,
18     pub(crate) package: String,
19     pub(crate) target: String,
20     pub(crate) target_kind: TargetKind,
21 }
22
23 impl CargoTargetSpec {
24     pub(crate) fn runnable_args(
25         snap: &GlobalStateSnapshot,
26         spec: Option<CargoTargetSpec>,
27         kind: &RunnableKind,
28         cfg: &Option<CfgExpr>,
29     ) -> Result<(Vec<String>, Vec<String>)> {
30         let mut args = Vec::new();
31         let mut extra_args = Vec::new();
32         match kind {
33             RunnableKind::Test { test_id, attr } => {
34                 args.push("test".to_string());
35                 if let Some(spec) = spec {
36                     spec.push_to(&mut args, kind);
37                 }
38                 extra_args.push(test_id.to_string());
39                 if let TestId::Path(_) = test_id {
40                     extra_args.push("--exact".to_string());
41                 }
42                 extra_args.push("--nocapture".to_string());
43                 if attr.ignore {
44                     extra_args.push("--ignored".to_string());
45                 }
46             }
47             RunnableKind::TestMod { path } => {
48                 args.push("test".to_string());
49                 if let Some(spec) = spec {
50                     spec.push_to(&mut args, kind);
51                 }
52                 extra_args.push(path.to_string());
53                 extra_args.push("--nocapture".to_string());
54             }
55             RunnableKind::Bench { test_id } => {
56                 args.push("bench".to_string());
57                 if let Some(spec) = spec {
58                     spec.push_to(&mut args, kind);
59                 }
60                 extra_args.push(test_id.to_string());
61                 if let TestId::Path(_) = test_id {
62                     extra_args.push("--exact".to_string());
63                 }
64                 extra_args.push("--nocapture".to_string());
65             }
66             RunnableKind::DocTest { test_id } => {
67                 args.push("test".to_string());
68                 args.push("--doc".to_string());
69                 if let Some(spec) = spec {
70                     spec.push_to(&mut args, kind);
71                 }
72                 extra_args.push(test_id.to_string());
73                 extra_args.push("--nocapture".to_string());
74             }
75             RunnableKind::Bin => {
76                 let subcommand = match spec {
77                     Some(CargoTargetSpec { target_kind: TargetKind::Test, .. }) => "test",
78                     _ => "run",
79                 };
80                 args.push(subcommand.to_string());
81                 if let Some(spec) = spec {
82                     spec.push_to(&mut args, kind);
83                 }
84             }
85         }
86
87         let cargo_config = snap.config.cargo();
88         if cargo_config.all_features {
89             args.push("--all-features".to_string());
90         } else {
91             let mut features = Vec::new();
92             if let Some(cfg) = cfg.as_ref() {
93                 required_features(cfg, &mut features);
94             }
95             for feature in cargo_config.features {
96                 features.push(feature.clone());
97             }
98             features.dedup();
99             for feature in features {
100                 args.push("--features".to_string());
101                 args.push(feature);
102             }
103         }
104
105         Ok((args, extra_args))
106     }
107
108     pub(crate) fn for_file(
109         global_state_snapshot: &GlobalStateSnapshot,
110         file_id: FileId,
111     ) -> Result<Option<CargoTargetSpec>> {
112         let crate_id = match global_state_snapshot.analysis.crate_for(file_id)?.first() {
113             Some(crate_id) => *crate_id,
114             None => return Ok(None),
115         };
116         let (cargo_ws, target) = match global_state_snapshot.cargo_target_for_crate_root(crate_id) {
117             Some(it) => it,
118             None => return Ok(None),
119         };
120
121         let target_data = &cargo_ws[target];
122         let package_data = &cargo_ws[target_data.package];
123         let res = CargoTargetSpec {
124             workspace_root: cargo_ws.workspace_root().to_path_buf(),
125             cargo_toml: package_data.manifest.clone(),
126             package: cargo_ws.package_flag(package_data),
127             target: target_data.name.clone(),
128             target_kind: target_data.kind,
129         };
130
131         Ok(Some(res))
132     }
133
134     pub(crate) fn push_to(self, buf: &mut Vec<String>, kind: &RunnableKind) {
135         buf.push("--package".to_string());
136         buf.push(self.package);
137
138         // Can't mix --doc with other target flags
139         if let RunnableKind::DocTest { .. } = kind {
140             return;
141         }
142         match self.target_kind {
143             TargetKind::Bin => {
144                 buf.push("--bin".to_string());
145                 buf.push(self.target);
146             }
147             TargetKind::Test => {
148                 buf.push("--test".to_string());
149                 buf.push(self.target);
150             }
151             TargetKind::Bench => {
152                 buf.push("--bench".to_string());
153                 buf.push(self.target);
154             }
155             TargetKind::Example => {
156                 buf.push("--example".to_string());
157                 buf.push(self.target);
158             }
159             TargetKind::Lib => {
160                 buf.push("--lib".to_string());
161             }
162             TargetKind::Other | TargetKind::BuildScript => (),
163         }
164     }
165 }
166
167 /// Fill minimal features needed
168 fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) {
169     match cfg_expr {
170         CfgExpr::Atom(CfgAtom::KeyValue { key, value }) if key == "feature" => {
171             features.push(value.to_string())
172         }
173         CfgExpr::All(preds) => {
174             preds.iter().for_each(|cfg| required_features(cfg, features));
175         }
176         CfgExpr::Any(preds) => {
177             for cfg in preds {
178                 let len_features = features.len();
179                 required_features(cfg, features);
180                 if len_features != features.len() {
181                     break;
182                 }
183             }
184         }
185         _ => {}
186     }
187 }
188
189 #[cfg(test)]
190 mod tests {
191     use super::*;
192
193     use cfg::CfgExpr;
194     use mbe::ast_to_token_tree;
195     use syntax::{
196         ast::{self, AstNode},
197         SmolStr,
198     };
199
200     fn check(cfg: &str, expected_features: &[&str]) {
201         let cfg_expr = {
202             let source_file = ast::SourceFile::parse(cfg).ok().unwrap();
203             let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
204             let (tt, _) = ast_to_token_tree(&tt);
205             CfgExpr::parse(&tt)
206         };
207
208         let mut features = vec![];
209         required_features(&cfg_expr, &mut features);
210
211         let expected_features =
212             expected_features.iter().map(|&it| SmolStr::new(it)).collect::<Vec<_>>();
213
214         assert_eq!(features, expected_features);
215     }
216
217     #[test]
218     fn test_cfg_expr_minimal_features_needed() {
219         check(r#"#![cfg(feature = "baz")]"#, &["baz"]);
220         check(r#"#![cfg(all(feature = "baz", feature = "foo"))]"#, &["baz", "foo"]);
221         check(r#"#![cfg(any(feature = "baz", feature = "foo", unix))]"#, &["baz"]);
222         check(r#"#![cfg(foo)]"#, &[]);
223     }
224 }