1 //! See `CargoTargetSpec`
3 use cfg::{CfgAtom, CfgExpr};
4 use ide::{FileId, RunnableKind, TestId};
5 use project_model::{self, ManifestPath, TargetKind};
8 use crate::{global_state::GlobalStateSnapshot, Result};
10 /// Abstract representation of Cargo target.
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.
15 pub(crate) struct CargoTargetSpec {
16 pub(crate) workspace_root: AbsPathBuf,
17 pub(crate) cargo_toml: ManifestPath,
18 pub(crate) package: String,
19 pub(crate) target: String,
20 pub(crate) target_kind: TargetKind,
23 impl CargoTargetSpec {
24 pub(crate) fn runnable_args(
25 snap: &GlobalStateSnapshot,
26 spec: Option<CargoTargetSpec>,
28 cfg: &Option<CfgExpr>,
29 ) -> Result<(Vec<String>, Vec<String>)> {
30 let mut args = Vec::new();
31 let mut extra_args = Vec::new();
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);
38 extra_args.push(test_id.to_string());
39 if let TestId::Path(_) = test_id {
40 extra_args.push("--exact".to_string());
42 extra_args.push("--nocapture".to_string());
44 extra_args.push("--ignored".to_string());
47 RunnableKind::TestMod { path } => {
48 args.push("test".to_string());
49 if let Some(spec) = spec {
50 spec.push_to(&mut args, kind);
52 extra_args.push(path.to_string());
53 extra_args.push("--nocapture".to_string());
55 RunnableKind::Bench { test_id } => {
56 args.push("bench".to_string());
57 if let Some(spec) = spec {
58 spec.push_to(&mut args, kind);
60 extra_args.push(test_id.to_string());
61 if let TestId::Path(_) = test_id {
62 extra_args.push("--exact".to_string());
64 extra_args.push("--nocapture".to_string());
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);
72 extra_args.push(test_id.to_string());
73 extra_args.push("--nocapture".to_string());
75 RunnableKind::Bin => {
76 let subcommand = match spec {
77 Some(CargoTargetSpec { target_kind: TargetKind::Test, .. }) => "test",
80 args.push(subcommand.to_string());
81 if let Some(spec) = spec {
82 spec.push_to(&mut args, kind);
87 let cargo_config = snap.config.cargo();
88 if cargo_config.all_features {
89 args.push("--all-features".to_string());
91 let mut features = Vec::new();
92 if let Some(cfg) = cfg.as_ref() {
93 required_features(cfg, &mut features);
95 for feature in cargo_config.features {
96 features.push(feature.clone());
99 for feature in features {
100 args.push("--features".to_string());
105 Ok((args, extra_args))
108 pub(crate) fn for_file(
109 global_state_snapshot: &GlobalStateSnapshot,
111 ) -> Result<Option<CargoTargetSpec>> {
112 let crate_id = match global_state_snapshot.analysis.crate_for(file_id)?.first() {
113 Some(crate_id) => *crate_id,
114 None => return Ok(None),
116 let (cargo_ws, target) = match global_state_snapshot.cargo_target_for_crate_root(crate_id) {
118 None => return Ok(None),
121 let target_data = &cargo_ws[target];
122 let package_data = &cargo_ws[target_data.package];
123 let res = CargoTargetSpec {
124 workspace_root: cargo_ws.workspace_root().to_path_buf(),
125 cargo_toml: package_data.manifest.clone(),
126 package: cargo_ws.package_flag(package_data),
127 target: target_data.name.clone(),
128 target_kind: target_data.kind,
134 pub(crate) fn push_to(self, buf: &mut Vec<String>, kind: &RunnableKind) {
135 buf.push("--package".to_string());
136 buf.push(self.package);
138 // Can't mix --doc with other target flags
139 if let RunnableKind::DocTest { .. } = kind {
142 match self.target_kind {
144 buf.push("--bin".to_string());
145 buf.push(self.target);
147 TargetKind::Test => {
148 buf.push("--test".to_string());
149 buf.push(self.target);
151 TargetKind::Bench => {
152 buf.push("--bench".to_string());
153 buf.push(self.target);
155 TargetKind::Example => {
156 buf.push("--example".to_string());
157 buf.push(self.target);
160 buf.push("--lib".to_string());
162 TargetKind::Other | TargetKind::BuildScript => (),
167 /// Fill minimal features needed
168 fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) {
170 CfgExpr::Atom(CfgAtom::KeyValue { key, value }) if key == "feature" => {
171 features.push(value.to_string())
173 CfgExpr::All(preds) => {
174 preds.iter().for_each(|cfg| required_features(cfg, features));
176 CfgExpr::Any(preds) => {
178 let len_features = features.len();
179 required_features(cfg, features);
180 if len_features != features.len() {
194 use mbe::syntax_node_to_token_tree;
196 ast::{self, AstNode},
200 fn check(cfg: &str, expected_features: &[&str]) {
202 let source_file = ast::SourceFile::parse(cfg).ok().unwrap();
203 let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
204 let (tt, _) = syntax_node_to_token_tree(tt.syntax());
208 let mut features = vec![];
209 required_features(&cfg_expr, &mut features);
211 let expected_features =
212 expected_features.iter().map(|&it| SmolStr::new(it)).collect::<Vec<_>>();
214 assert_eq!(features, expected_features);
218 fn test_cfg_expr_minimal_features_needed() {
219 check(r#"#![cfg(feature = "baz")]"#, &["baz"]);
220 check(r#"#![cfg(all(feature = "baz", feature = "foo"))]"#, &["baz", "foo"]);
221 check(r#"#![cfg(any(feature = "baz", feature = "foo", unix))]"#, &["baz"]);
222 check(r#"#![cfg(foo)]"#, &[]);