1 //! See `CargoTargetSpec`
3 use cfg::{CfgAtom, CfgExpr};
4 use ide::{FileId, RunnableKind, TestId};
5 use project_model::{self, 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: AbsPathBuf,
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 if snap.config.cargo.all_features {
88 args.push("--all-features".to_string());
90 let mut features = Vec::new();
91 if let Some(cfg) = cfg.as_ref() {
92 required_features(cfg, &mut features);
94 for feature in &snap.config.cargo.features {
95 features.push(feature.clone());
98 for feature in features {
99 args.push("--features".to_string());
104 Ok((args, extra_args))
107 pub(crate) fn for_file(
108 global_state_snapshot: &GlobalStateSnapshot,
110 ) -> Result<Option<CargoTargetSpec>> {
111 let crate_id = match global_state_snapshot.analysis.crate_for(file_id)?.first() {
112 Some(crate_id) => *crate_id,
113 None => return Ok(None),
115 let (cargo_ws, target) = match global_state_snapshot.cargo_target_for_crate_root(crate_id) {
117 None => return Ok(None),
120 let target_data = &cargo_ws[target];
121 let package_data = &cargo_ws[target_data.package];
122 let res = CargoTargetSpec {
123 workspace_root: cargo_ws.workspace_root().to_path_buf(),
124 cargo_toml: package_data.manifest.clone(),
125 package: cargo_ws.package_flag(&package_data),
126 target: target_data.name.clone(),
127 target_kind: target_data.kind,
133 pub(crate) fn push_to(self, buf: &mut Vec<String>, kind: &RunnableKind) {
134 buf.push("--package".to_string());
135 buf.push(self.package);
137 // Can't mix --doc with other target flags
138 if let RunnableKind::DocTest { .. } = kind {
141 match self.target_kind {
143 buf.push("--bin".to_string());
144 buf.push(self.target);
146 TargetKind::Test => {
147 buf.push("--test".to_string());
148 buf.push(self.target);
150 TargetKind::Bench => {
151 buf.push("--bench".to_string());
152 buf.push(self.target);
154 TargetKind::Example => {
155 buf.push("--example".to_string());
156 buf.push(self.target);
159 buf.push("--lib".to_string());
161 TargetKind::Other => (),
166 /// Fill minimal features needed
167 fn required_features(cfg_expr: &CfgExpr, features: &mut Vec<String>) {
169 CfgExpr::Atom(CfgAtom::KeyValue { key, value }) if key == "feature" => {
170 features.push(value.to_string())
172 CfgExpr::All(preds) => {
173 preds.iter().for_each(|cfg| required_features(cfg, features));
175 CfgExpr::Any(preds) => {
177 let len_features = features.len();
178 required_features(cfg, features);
179 if len_features != features.len() {
193 use mbe::ast_to_token_tree;
195 ast::{self, AstNode},
199 fn check(cfg: &str, expected_features: &[&str]) {
201 let source_file = ast::SourceFile::parse(cfg).ok().unwrap();
202 let tt = source_file.syntax().descendants().find_map(ast::TokenTree::cast).unwrap();
203 let (tt, _) = ast_to_token_tree(&tt).unwrap();
207 let mut features = vec![];
208 required_features(&cfg_expr, &mut features);
210 let expected_features =
211 expected_features.iter().map(|&it| SmolStr::new(it)).collect::<Vec<_>>();
213 assert_eq!(features, expected_features);
217 fn test_cfg_expr_minimal_features_needed() {
218 check(r#"#![cfg(feature = "baz")]"#, &["baz"]);
219 check(r#"#![cfg(all(feature = "baz", feature = "foo"))]"#, &["baz", "foo"]);
220 check(r#"#![cfg(any(feature = "baz", feature = "foo", unix))]"#, &["baz"]);
221 check(r#"#![cfg(foo)]"#, &[]);