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