1 //! See `CargoTargetSpec`
5 use cfg::{CfgAtom, CfgExpr};
6 use ide::{FileId, RunnableKind, TestId};
7 use project_model::{self, CargoFeatures, ManifestPath, TargetKind};
10 use crate::{global_state::GlobalStateSnapshot, Result};
12 /// Abstract representation of Cargo target.
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.
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>,
26 impl CargoTargetSpec {
27 pub(crate) fn runnable_args(
28 snap: &GlobalStateSnapshot,
29 spec: Option<CargoTargetSpec>,
31 cfg: &Option<CfgExpr>,
32 ) -> Result<(Vec<String>, Vec<String>)> {
33 let mut args = Vec::new();
34 let mut extra_args = Vec::new();
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());
43 extra_args.push("--nocapture".to_owned());
45 extra_args.push("--ignored".to_owned());
48 RunnableKind::TestMod { path } => {
49 args.push("test".to_owned());
50 extra_args.push(path.clone());
51 extra_args.push("--nocapture".to_owned());
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());
59 extra_args.push("--nocapture".to_owned());
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());
67 RunnableKind::Bin => {
68 let subcommand = match spec {
69 Some(CargoTargetSpec { target_kind: TargetKind::Test, .. }) => "test",
72 args.push(subcommand.to_owned());
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);
84 let cargo_config = snap.config.cargo();
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());
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);
100 feats.extend(features.iter().cloned());
101 feats.extend(target_required_features);
104 for feature in feats {
105 args.push("--features".to_owned());
109 if *no_default_features {
110 args.push("--no-default-features".to_owned());
114 Ok((args, extra_args))
117 pub(crate) fn for_file(
118 global_state_snapshot: &GlobalStateSnapshot,
120 ) -> Result<Option<CargoTargetSpec>> {
121 let crate_id = match &*global_state_snapshot.analysis.crates_for(file_id)? {
122 &[crate_id, ..] => crate_id,
123 _ => return Ok(None),
125 let (cargo_ws, target) = match global_state_snapshot.cargo_target_for_crate_root(crate_id) {
127 None => return Ok(None),
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(),
144 pub(crate) fn push_to(self, buf: &mut Vec<String>, kind: &RunnableKind) {
145 buf.push("--package".to_owned());
146 buf.push(self.package);
148 // Can't mix --doc with other target flags
149 if let RunnableKind::DocTest { .. } = kind {
152 match self.target_kind {
154 buf.push("--bin".to_owned());
155 buf.push(self.target);
157 TargetKind::Test => {
158 buf.push("--test".to_owned());
159 buf.push(self.target);
161 TargetKind::Bench => {
162 buf.push("--bench".to_owned());
163 buf.push(self.target);
165 TargetKind::Example => {
166 buf.push("--example".to_owned());
167 buf.push(self.target);
170 buf.push("--lib".to_owned());
172 TargetKind::Other | TargetKind::BuildScript => (),
177 /// Fill minimal features needed
178 fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) {
180 CfgExpr::Atom(CfgAtom::KeyValue { key, value }) if key == "feature" => {
181 features.push(value.to_string())
183 CfgExpr::All(preds) => {
184 preds.iter().for_each(|cfg| required_features(cfg, features));
186 CfgExpr::Any(preds) => {
188 let len_features = features.len();
189 required_features(cfg, features);
190 if len_features != features.len() {
204 use mbe::syntax_node_to_token_tree;
206 ast::{self, AstNode},
210 fn check(cfg: &str, expected_features: &[&str]) {
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());
218 let mut features = vec![];
219 required_features(&cfg_expr, &mut features);
221 let expected_features =
222 expected_features.iter().map(|&it| SmolStr::new(it)).collect::<Vec<_>>();
224 assert_eq!(features, expected_features);
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)]"#, &[]);