]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/cargo_target_spec.rs
Open Cargo.toml opens more specific manifest
[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         if snap.config.cargo.all_features {
88             args.push("--all-features".to_string());
89         } else {
90             let mut features = Vec::new();
91             if let Some(cfg) = cfg.as_ref() {
92                 required_features(cfg, &mut features);
93             }
94             for feature in &snap.config.cargo.features {
95                 features.push(feature.clone());
96             }
97             features.dedup();
98             for feature in features {
99                 args.push("--features".to_string());
100                 args.push(feature);
101             }
102         }
103
104         Ok((args, extra_args))
105     }
106
107     pub(crate) fn for_file(
108         global_state_snapshot: &GlobalStateSnapshot,
109         file_id: FileId,
110     ) -> Result<Option<CargoTargetSpec>> {
111         let crate_id = match global_state_snapshot.analysis.crate_for(file_id)?.first() {
112             Some(crate_id) => *crate_id,
113             None => return Ok(None),
114         };
115         let (cargo_ws, target) = match global_state_snapshot.cargo_target_for_crate_root(crate_id) {
116             Some(it) => it,
117             None => return Ok(None),
118         };
119
120         let target_data = &cargo_ws[target];
121         let package_data = &cargo_ws[target_data.package];
122         let res = CargoTargetSpec {
123             workspace_root: cargo_ws.workspace_root().to_path_buf(),
124             cargo_toml: package_data.manifest.clone(),
125             package: cargo_ws.package_flag(&package_data),
126             target: target_data.name.clone(),
127             target_kind: target_data.kind,
128         };
129
130         Ok(Some(res))
131     }
132
133     pub(crate) fn push_to(self, buf: &mut Vec<String>, kind: &RunnableKind) {
134         buf.push("--package".to_string());
135         buf.push(self.package);
136
137         // Can't mix --doc with other target flags
138         if let RunnableKind::DocTest { .. } = kind {
139             return;
140         }
141         match self.target_kind {
142             TargetKind::Bin => {
143                 buf.push("--bin".to_string());
144                 buf.push(self.target);
145             }
146             TargetKind::Test => {
147                 buf.push("--test".to_string());
148                 buf.push(self.target);
149             }
150             TargetKind::Bench => {
151                 buf.push("--bench".to_string());
152                 buf.push(self.target);
153             }
154             TargetKind::Example => {
155                 buf.push("--example".to_string());
156                 buf.push(self.target);
157             }
158             TargetKind::Lib => {
159                 buf.push("--lib".to_string());
160             }
161             TargetKind::Other => (),
162         }
163     }
164 }
165
166 /// Fill minimal features needed
167 fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) {
168     match cfg_expr {
169         CfgExpr::Atom(CfgAtom::KeyValue { key, value }) if key == "feature" => {
170             features.push(value.to_string())
171         }
172         CfgExpr::All(preds) => {
173             preds.iter().for_each(|cfg| required_features(cfg, features));
174         }
175         CfgExpr::Any(preds) => {
176             for cfg in preds {
177                 let len_features = features.len();
178                 required_features(cfg, features);
179                 if len_features != features.len() {
180                     break;
181                 }
182             }
183         }
184         _ => {}
185     }
186 }
187
188 #[cfg(test)]
189 mod tests {
190     use super::*;
191
192     use cfg::CfgExpr;
193     use mbe::ast_to_token_tree;
194     use syntax::{
195         ast::{self, AstNode},
196         SmolStr,
197     };
198
199     fn check(cfg: &str, expected_features: &[&str]) {
200         let cfg_expr = {
201             let source_file = ast::SourceFile::parse(cfg).ok().unwrap();
202             let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
203             let (tt, _) = ast_to_token_tree(&tt).unwrap();
204             CfgExpr::parse(&tt)
205         };
206
207         let mut features = vec![];
208         required_features(&cfg_expr, &mut features);
209
210         let expected_features =
211             expected_features.iter().map(|&it| SmolStr::new(it)).collect::<Vec<_>>();
212
213         assert_eq!(features, expected_features);
214     }
215
216     #[test]
217     fn test_cfg_expr_minimal_features_needed() {
218         check(r#"#![cfg(feature = "baz")]"#, &["baz"]);
219         check(r#"#![cfg(all(feature = "baz", feature = "foo"))]"#, &["baz", "foo"]);
220         check(r#"#![cfg(any(feature = "baz", feature = "foo", unix))]"#, &["baz"]);
221         check(r#"#![cfg(foo)]"#, &[]);
222     }
223 }