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