]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/rust-analyzer/src/cargo_target_spec.rs
Rollup merge of #102883 - Urgau:fix-stabilization-half_open_range_patterns, r=lcnr
[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, CargoFeatures, 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_owned());
39                 extra_args.push(test_id.to_string());
40                 if let TestId::Path(_) = test_id {
41                     extra_args.push("--exact".to_owned());
42                 }
43                 extra_args.push("--nocapture".to_owned());
44                 if attr.ignore {
45                     extra_args.push("--ignored".to_owned());
46                 }
47             }
48             RunnableKind::TestMod { path } => {
49                 args.push("test".to_owned());
50                 extra_args.push(path.clone());
51                 extra_args.push("--nocapture".to_owned());
52             }
53             RunnableKind::Bench { test_id } => {
54                 args.push("bench".to_owned());
55                 extra_args.push(test_id.to_string());
56                 if let TestId::Path(_) = test_id {
57                     extra_args.push("--exact".to_owned());
58                 }
59                 extra_args.push("--nocapture".to_owned());
60             }
61             RunnableKind::DocTest { test_id } => {
62                 args.push("test".to_owned());
63                 args.push("--doc".to_owned());
64                 extra_args.push(test_id.to_string());
65                 extra_args.push("--nocapture".to_owned());
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_owned());
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
86         match &cargo_config.features {
87             CargoFeatures::All => {
88                 args.push("--all-features".to_owned());
89                 for feature in target_required_features {
90                     args.push("--features".to_owned());
91                     args.push(feature);
92                 }
93             }
94             CargoFeatures::Selected { features, no_default_features } => {
95                 let mut feats = Vec::new();
96                 if let Some(cfg) = cfg.as_ref() {
97                     required_features(cfg, &mut feats);
98                 }
99
100                 feats.extend(features.iter().cloned());
101                 feats.extend(target_required_features);
102
103                 feats.dedup();
104                 for feature in feats {
105                     args.push("--features".to_owned());
106                     args.push(feature);
107                 }
108
109                 if *no_default_features {
110                     args.push("--no-default-features".to_owned());
111                 }
112             }
113         }
114         Ok((args, extra_args))
115     }
116
117     pub(crate) fn for_file(
118         global_state_snapshot: &GlobalStateSnapshot,
119         file_id: FileId,
120     ) -> Result<Option<CargoTargetSpec>> {
121         let crate_id = match &*global_state_snapshot.analysis.crate_for(file_id)? {
122             &[crate_id, ..] => crate_id,
123             _ => return Ok(None),
124         };
125         let (cargo_ws, target) = match global_state_snapshot.cargo_target_for_crate_root(crate_id) {
126             Some(it) => it,
127             None => return Ok(None),
128         };
129
130         let target_data = &cargo_ws[target];
131         let package_data = &cargo_ws[target_data.package];
132         let res = CargoTargetSpec {
133             workspace_root: cargo_ws.workspace_root().to_path_buf(),
134             cargo_toml: package_data.manifest.clone(),
135             package: cargo_ws.package_flag(package_data),
136             target: target_data.name.clone(),
137             target_kind: target_data.kind,
138             required_features: target_data.required_features.clone(),
139         };
140
141         Ok(Some(res))
142     }
143
144     pub(crate) fn push_to(self, buf: &mut Vec<String>, kind: &RunnableKind) {
145         buf.push("--package".to_owned());
146         buf.push(self.package);
147
148         // Can't mix --doc with other target flags
149         if let RunnableKind::DocTest { .. } = kind {
150             return;
151         }
152         match self.target_kind {
153             TargetKind::Bin => {
154                 buf.push("--bin".to_owned());
155                 buf.push(self.target);
156             }
157             TargetKind::Test => {
158                 buf.push("--test".to_owned());
159                 buf.push(self.target);
160             }
161             TargetKind::Bench => {
162                 buf.push("--bench".to_owned());
163                 buf.push(self.target);
164             }
165             TargetKind::Example => {
166                 buf.push("--example".to_owned());
167                 buf.push(self.target);
168             }
169             TargetKind::Lib => {
170                 buf.push("--lib".to_owned());
171             }
172             TargetKind::Other | TargetKind::BuildScript => (),
173         }
174     }
175 }
176
177 /// Fill minimal features needed
178 fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) {
179     match cfg_expr {
180         CfgExpr::Atom(CfgAtom::KeyValue { key, value }) if key == "feature" => {
181             features.push(value.to_string())
182         }
183         CfgExpr::All(preds) => {
184             preds.iter().for_each(|cfg| required_features(cfg, features));
185         }
186         CfgExpr::Any(preds) => {
187             for cfg in preds {
188                 let len_features = features.len();
189                 required_features(cfg, features);
190                 if len_features != features.len() {
191                     break;
192                 }
193             }
194         }
195         _ => {}
196     }
197 }
198
199 #[cfg(test)]
200 mod tests {
201     use super::*;
202
203     use cfg::CfgExpr;
204     use mbe::syntax_node_to_token_tree;
205     use syntax::{
206         ast::{self, AstNode},
207         SmolStr,
208     };
209
210     fn check(cfg: &str, expected_features: &[&str]) {
211         let cfg_expr = {
212             let source_file = ast::SourceFile::parse(cfg).ok().unwrap();
213             let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
214             let (tt, _) = syntax_node_to_token_tree(tt.syntax());
215             CfgExpr::parse(&tt)
216         };
217
218         let mut features = vec![];
219         required_features(&cfg_expr, &mut features);
220
221         let expected_features =
222             expected_features.iter().map(|&it| SmolStr::new(it)).collect::<Vec<_>>();
223
224         assert_eq!(features, expected_features);
225     }
226
227     #[test]
228     fn test_cfg_expr_minimal_features_needed() {
229         check(r#"#![cfg(feature = "baz")]"#, &["baz"]);
230         check(r#"#![cfg(all(feature = "baz", feature = "foo"))]"#, &["baz", "foo"]);
231         check(r#"#![cfg(any(feature = "baz", feature = "foo", unix))]"#, &["baz"]);
232         check(r#"#![cfg(foo)]"#, &[]);
233     }
234 }