Skip to main content

cargo/workspace/parser/
targets.rs

1//! This module implements Cargo conventions for directory layout:
2//!
3//!  * `src/lib.rs` is a library
4//!  * `src/main.rs` is a binary
5//!  * `src/bin/*.rs` are binaries
6//!  * `examples/*.rs` are examples
7//!  * `tests/*.rs` are integration tests
8//!  * `benches/*.rs` are benchmarks
9//!
10//! It is a bit tricky because we need match explicit information from `Cargo.toml`
11//! with implicit info in directory layout.
12
13use crate::util::data_structures::{HashMap, HashSet};
14use std::fmt::Write;
15use std::fs::{self, DirEntry};
16use std::path::{Path, PathBuf};
17
18use anyhow::Context as _;
19use cargo_util::paths;
20use cargo_util_schemas::manifest::{
21    PathValue, StringOrVec, TomlBenchTarget, TomlBinTarget, TomlExampleTarget, TomlLibTarget,
22    TomlManifest, TomlPackageBuild, TomlTarget, TomlTestTarget,
23};
24
25use crate::compiler::{CrateType, rustdoc::RustdocScrapeExamples};
26use crate::util::{closest_msg, errors::CargoResult, restricted_names};
27use crate::workspace::parser::deprecated_underscore;
28use crate::workspace::{Edition, Feature, Features, Target};
29
30const DEFAULT_TEST_DIR_NAME: &'static str = "tests";
31const DEFAULT_BENCH_DIR_NAME: &'static str = "benches";
32const DEFAULT_EXAMPLE_DIR_NAME: &'static str = "examples";
33
34const TARGET_KIND_HUMAN_LIB: &str = "library";
35const TARGET_KIND_HUMAN_BIN: &str = "binary";
36const TARGET_KIND_HUMAN_EXAMPLE: &str = "example";
37const TARGET_KIND_HUMAN_TEST: &str = "test";
38const TARGET_KIND_HUMAN_BENCH: &str = "benchmark";
39
40const TARGET_KIND_LIB: &str = "lib";
41const TARGET_KIND_BIN: &str = "bin";
42const TARGET_KIND_EXAMPLE: &str = "example";
43const TARGET_KIND_TEST: &str = "test";
44const TARGET_KIND_BENCH: &str = "bench";
45
46#[tracing::instrument(skip_all)]
47pub(super) fn to_targets(
48    features: &Features,
49    original_toml: &TomlManifest,
50    normalized_toml: &TomlManifest,
51    package_root: &Path,
52    edition: Edition,
53    metabuild: &Option<StringOrVec>,
54    warnings: &mut Vec<String>,
55) -> CargoResult<Vec<Target>> {
56    let mut targets = Vec::new();
57
58    if let Some(target) = to_lib_target(
59        original_toml.lib.as_ref(),
60        normalized_toml.lib.as_ref(),
61        package_root,
62        edition,
63        warnings,
64    )? {
65        targets.push(target);
66    }
67
68    let package = normalized_toml
69        .package
70        .as_ref()
71        .ok_or_else(|| anyhow::format_err!("manifest has no `package` (or `project`)"))?;
72
73    targets.extend(to_bin_targets(
74        features,
75        normalized_toml.bin.as_deref().unwrap_or_default(),
76        package_root,
77        edition,
78        warnings,
79    )?);
80
81    targets.extend(to_example_targets(
82        normalized_toml.example.as_deref().unwrap_or_default(),
83        package_root,
84        edition,
85        warnings,
86    )?);
87
88    targets.extend(to_test_targets(
89        normalized_toml.test.as_deref().unwrap_or_default(),
90        package_root,
91        edition,
92        warnings,
93    )?);
94
95    targets.extend(to_bench_targets(
96        normalized_toml.bench.as_deref().unwrap_or_default(),
97        package_root,
98        edition,
99        warnings,
100    )?);
101
102    // processing the custom build script
103    if let Some(custom_build) = package.normalized_build().expect("previously normalized") {
104        if metabuild.is_some() {
105            anyhow::bail!("cannot specify both `metabuild` and `build`");
106        }
107        validate_unique_build_scripts(custom_build)?;
108        for script in custom_build {
109            let script_path = Path::new(script);
110            let name = format!(
111                "build-script-{}",
112                script_path
113                    .file_stem()
114                    .and_then(|s| s.to_str())
115                    .expect("previously normalized")
116            );
117            targets.push(Target::custom_build_target(
118                &name,
119                package_root.join(script_path),
120                edition,
121            ));
122        }
123    }
124    if let Some(metabuild) = metabuild {
125        // Verify names match available build deps.
126        let bdeps = normalized_toml.build_dependencies.as_ref();
127        for name in &metabuild.0 {
128            if !bdeps.map_or(false, |bd| bd.contains_key(name.as_str())) {
129                anyhow::bail!(
130                    "metabuild package `{}` must be specified in `build-dependencies`",
131                    name
132                );
133            }
134        }
135
136        targets.push(Target::metabuild_target(&format!(
137            "metabuild-{}",
138            package.normalized_name().expect("previously normalized")
139        )));
140    }
141
142    Ok(targets)
143}
144
145#[tracing::instrument(skip_all)]
146pub fn normalize_lib(
147    original_lib: Option<&TomlLibTarget>,
148    package_root: &Path,
149    package_name: &str,
150    edition: Edition,
151    autodiscover: Option<bool>,
152    warnings: &mut Vec<String>,
153) -> CargoResult<Option<TomlLibTarget>> {
154    if is_normalized(original_lib, autodiscover) {
155        let Some(mut lib) = original_lib.cloned() else {
156            return Ok(None);
157        };
158
159        // Check early to improve error messages
160        validate_lib_name(&lib, warnings)?;
161
162        validate_proc_macro(&lib, TARGET_KIND_HUMAN_LIB, edition, warnings)?;
163        validate_crate_types(&lib, TARGET_KIND_HUMAN_LIB, edition, warnings)?;
164
165        if let Some(PathValue(path)) = &lib.path {
166            lib.path = Some(PathValue(paths::normalize_path(path).into()));
167        }
168
169        Ok(Some(lib))
170    } else {
171        let inferred = inferred_lib(package_root);
172        let lib = original_lib.cloned().or_else(|| {
173            inferred.as_ref().map(|lib| TomlTarget {
174                path: Some(PathValue(lib.clone())),
175                ..TomlTarget::new()
176            })
177        });
178        let Some(mut lib) = lib else { return Ok(None) };
179        lib.name
180            .get_or_insert_with(|| package_name.replace("-", "_"));
181
182        // Check early to improve error messages
183        validate_lib_name(&lib, warnings)?;
184
185        validate_proc_macro(&lib, TARGET_KIND_HUMAN_LIB, edition, warnings)?;
186        validate_crate_types(&lib, TARGET_KIND_HUMAN_LIB, edition, warnings)?;
187
188        if lib.path.is_none() {
189            if let Some(inferred) = inferred {
190                lib.path = Some(PathValue(inferred));
191            } else {
192                let name = name_or_panic(&lib);
193                let legacy_path = Path::new("src").join(format!("{name}.rs"));
194                if edition == Edition::Edition2015 && package_root.join(&legacy_path).exists() {
195                    warnings.push(format!(
196                        "path `{}` was erroneously implicitly accepted for library `{name}`,\n\
197                     please rename the file to `src/lib.rs` or set lib.path in Cargo.toml",
198                        legacy_path.display(),
199                    ));
200                    lib.path = Some(PathValue(legacy_path));
201                } else {
202                    anyhow::bail!(
203                        "can't find library `{name}`, \
204                     rename file to `src/lib.rs` or specify lib.path",
205                    )
206                }
207            }
208        }
209
210        if let Some(PathValue(path)) = lib.path.as_ref() {
211            lib.path = Some(PathValue(paths::normalize_path(&path).into()));
212        }
213
214        Ok(Some(lib))
215    }
216}
217
218#[tracing::instrument(skip_all)]
219fn to_lib_target(
220    original_lib: Option<&TomlLibTarget>,
221    normalized_lib: Option<&TomlLibTarget>,
222    package_root: &Path,
223    edition: Edition,
224    warnings: &mut Vec<String>,
225) -> CargoResult<Option<Target>> {
226    let Some(lib) = normalized_lib else {
227        return Ok(None);
228    };
229
230    let path = lib.path.as_ref().expect("previously normalized");
231    let path = package_root.join(&path.0);
232
233    // Per the Macros 1.1 RFC:
234    //
235    // > Initially if a crate is compiled with the `proc-macro` crate type
236    // > (and possibly others) it will forbid exporting any items in the
237    // > crate other than those functions tagged #[proc_macro_derive] and
238    // > those functions must also be placed at the crate root.
239    //
240    // A plugin requires exporting plugin_registrar so a crate cannot be
241    // both at once.
242    let proc_macro = lib.proc_macro().unwrap_or(false);
243    let crate_types = match (lib.crate_types(), proc_macro) {
244        (Some(kinds), _)
245            if kinds.contains(&CrateType::Dylib.as_str().to_owned())
246                && kinds.contains(&CrateType::Cdylib.as_str().to_owned()) =>
247        {
248            anyhow::bail!(format!(
249                "library `{}` cannot set the crate type of both `dylib` and `cdylib`",
250                name_or_panic(lib)
251            ));
252        }
253        (Some(kinds), _) if kinds.contains(&"proc-macro".to_string()) => {
254            warnings.push(format!(
255                "library `{}` should only specify `proc-macro = true` instead of setting `crate-type`",
256                name_or_panic(lib)
257            ));
258            if kinds.len() > 1 {
259                anyhow::bail!("cannot mix `proc-macro` crate type with others");
260            }
261            vec![CrateType::ProcMacro]
262        }
263        (Some(kinds), _) => kinds.iter().map(|s| s.into()).collect(),
264        (None, true) => vec![CrateType::ProcMacro],
265        (None, false) => vec![CrateType::Lib],
266    };
267
268    if proc_macro != crate_types.contains(&CrateType::ProcMacro) {
269        let help = if proc_macro {
270            "remove `proc-macro` if this library is not intended to be a proc macro"
271        } else {
272            "set `proc-macro = true` and remove `crate-type` \
273             if this library is intended to be a proc macro"
274        };
275        warnings.push(format!(
276            "library `{}` has conflicting `proc-macro = {proc_macro}` and `crate-type` settings\n\
277             note: this was previously accepted but will become a hard error in the future; \
278             see <https://github.com/rust-lang/cargo/issues/17579>\n\
279             help: {help}",
280            name_or_panic(lib)
281        ));
282    }
283
284    let mut target = Target::lib_target(name_or_panic(lib), crate_types, path, edition);
285    configure(lib, &mut target, TARGET_KIND_HUMAN_LIB, warnings)?;
286    target.set_name_inferred(original_lib.map_or(true, |v| v.name.is_none()));
287    Ok(Some(target))
288}
289
290#[tracing::instrument(skip_all)]
291pub fn normalize_bins(
292    toml_bins: Option<&Vec<TomlBinTarget>>,
293    package_root: &Path,
294    package_name: &str,
295    edition: Edition,
296    autodiscover: Option<bool>,
297    warnings: &mut Vec<String>,
298    errors: &mut Vec<String>,
299    has_lib: bool,
300) -> CargoResult<Vec<TomlBinTarget>> {
301    if are_normalized(toml_bins, autodiscover) {
302        let mut toml_bins = toml_bins.cloned().unwrap_or_default();
303        for bin in toml_bins.iter_mut() {
304            validate_bin_name(bin, warnings)?;
305            validate_bin_crate_types(bin, edition, warnings, errors)?;
306            validate_bin_proc_macro(bin, edition, warnings, errors)?;
307
308            if let Some(PathValue(path)) = &bin.path {
309                bin.path = Some(PathValue(paths::normalize_path(path).into()));
310            }
311        }
312        Ok(toml_bins)
313    } else {
314        let inferred = inferred_bins(package_root, package_name);
315
316        let mut bins = toml_targets_and_inferred(
317            toml_bins,
318            &inferred,
319            package_root,
320            autodiscover,
321            edition,
322            warnings,
323            TARGET_KIND_HUMAN_BIN,
324            TARGET_KIND_BIN,
325            "autobins",
326        );
327
328        for bin in &mut bins {
329            // Check early to improve error messages
330            validate_bin_name(bin, warnings)?;
331
332            validate_bin_crate_types(bin, edition, warnings, errors)?;
333            validate_bin_proc_macro(bin, edition, warnings, errors)?;
334
335            let path = target_path(
336                bin,
337                &inferred,
338                TARGET_KIND_BIN,
339                package_root,
340                edition,
341                &mut |_| {
342                    if let Some(legacy_path) =
343                        legacy_bin_path(package_root, name_or_panic(bin), has_lib)
344                    {
345                        warnings.push(format!(
346                            "path `{}` was erroneously implicitly accepted for binary `{}`,\n\
347                     please set bin.path in Cargo.toml",
348                            legacy_path.display(),
349                            name_or_panic(bin)
350                        ));
351                        Some(legacy_path)
352                    } else {
353                        None
354                    }
355                },
356            );
357            let path = match path {
358                Ok(path) => paths::normalize_path(&path).into(),
359                Err(e) => anyhow::bail!("{}", e),
360            };
361            bin.path = Some(PathValue(path));
362        }
363
364        Ok(bins)
365    }
366}
367
368#[tracing::instrument(skip_all)]
369fn to_bin_targets(
370    features: &Features,
371    bins: &[TomlBinTarget],
372    package_root: &Path,
373    edition: Edition,
374    warnings: &mut Vec<String>,
375) -> CargoResult<Vec<Target>> {
376    // This loop performs basic checks on each of the TomlTarget in `bins`.
377    for bin in bins {
378        // For each binary, check if the `filename` parameter is populated. If it is,
379        // check if the corresponding cargo feature has been activated.
380        if bin.filename.is_some() {
381            features.require(Feature::different_binary_name())?;
382        }
383    }
384
385    validate_unique_names(&bins, TARGET_KIND_HUMAN_BIN)?;
386
387    let mut result = Vec::with_capacity(bins.len());
388    for bin in bins {
389        let path = package_root.join(&bin.path.as_ref().expect("previously normalized").0);
390        let mut target = Target::bin_target(
391            name_or_panic(bin),
392            bin.filename.clone(),
393            path,
394            bin.required_features.clone(),
395            edition,
396        );
397
398        configure(bin, &mut target, TARGET_KIND_HUMAN_BIN, warnings)?;
399        result.push(target);
400    }
401    Ok(result)
402}
403
404fn legacy_bin_path(package_root: &Path, name: &str, has_lib: bool) -> Option<PathBuf> {
405    if !has_lib {
406        let rel_path = Path::new("src").join(format!("{}.rs", name));
407        if package_root.join(&rel_path).exists() {
408            return Some(rel_path);
409        }
410    }
411
412    let rel_path = Path::new("src").join("main.rs");
413    if package_root.join(&rel_path).exists() {
414        return Some(rel_path);
415    }
416
417    let default_bin_dir_name = Path::new("src").join("bin");
418    let rel_path = default_bin_dir_name.join("main.rs");
419    if package_root.join(&rel_path).exists() {
420        return Some(rel_path);
421    }
422    None
423}
424
425#[tracing::instrument(skip_all)]
426pub fn normalize_examples(
427    toml_examples: Option<&Vec<TomlExampleTarget>>,
428    package_root: &Path,
429    edition: Edition,
430    autodiscover: Option<bool>,
431    warnings: &mut Vec<String>,
432    errors: &mut Vec<String>,
433) -> CargoResult<Vec<TomlExampleTarget>> {
434    let mut inferred = || infer_from_directory(&package_root, Path::new(DEFAULT_EXAMPLE_DIR_NAME));
435
436    let targets = normalize_targets(
437        TARGET_KIND_HUMAN_EXAMPLE,
438        TARGET_KIND_EXAMPLE,
439        toml_examples,
440        &mut inferred,
441        package_root,
442        edition,
443        autodiscover,
444        warnings,
445        errors,
446        "autoexamples",
447    )?;
448
449    Ok(targets)
450}
451
452#[tracing::instrument(skip_all)]
453fn to_example_targets(
454    targets: &[TomlExampleTarget],
455    package_root: &Path,
456    edition: Edition,
457    warnings: &mut Vec<String>,
458) -> CargoResult<Vec<Target>> {
459    validate_unique_names(&targets, TARGET_KIND_EXAMPLE)?;
460
461    let mut result = Vec::with_capacity(targets.len());
462    for toml in targets {
463        let path = package_root.join(&toml.path.as_ref().expect("previously normalized").0);
464        let crate_types = match toml.crate_types() {
465            Some(kinds) => kinds.iter().map(|s| s.into()).collect(),
466            None => Vec::new(),
467        };
468
469        let mut target = Target::example_target(
470            name_or_panic(&toml),
471            crate_types,
472            path,
473            toml.required_features.clone(),
474            edition,
475        );
476        configure(&toml, &mut target, TARGET_KIND_HUMAN_EXAMPLE, warnings)?;
477        result.push(target);
478    }
479
480    Ok(result)
481}
482
483#[tracing::instrument(skip_all)]
484pub fn normalize_tests(
485    toml_tests: Option<&Vec<TomlTestTarget>>,
486    package_root: &Path,
487    edition: Edition,
488    autodiscover: Option<bool>,
489    warnings: &mut Vec<String>,
490    errors: &mut Vec<String>,
491) -> CargoResult<Vec<TomlTestTarget>> {
492    let mut inferred = || infer_from_directory(&package_root, Path::new(DEFAULT_TEST_DIR_NAME));
493
494    let targets = normalize_targets(
495        TARGET_KIND_HUMAN_TEST,
496        TARGET_KIND_TEST,
497        toml_tests,
498        &mut inferred,
499        package_root,
500        edition,
501        autodiscover,
502        warnings,
503        errors,
504        "autotests",
505    )?;
506
507    Ok(targets)
508}
509
510#[tracing::instrument(skip_all)]
511fn to_test_targets(
512    targets: &[TomlTestTarget],
513    package_root: &Path,
514    edition: Edition,
515    warnings: &mut Vec<String>,
516) -> CargoResult<Vec<Target>> {
517    validate_unique_names(&targets, TARGET_KIND_TEST)?;
518
519    let mut result = Vec::with_capacity(targets.len());
520    for toml in targets {
521        let path = package_root.join(&toml.path.as_ref().expect("previously normalized").0);
522        let mut target = Target::test_target(
523            name_or_panic(&toml),
524            path,
525            toml.required_features.clone(),
526            edition,
527        );
528        configure(&toml, &mut target, TARGET_KIND_HUMAN_TEST, warnings)?;
529        result.push(target);
530    }
531    Ok(result)
532}
533
534#[tracing::instrument(skip_all)]
535pub fn normalize_benches(
536    toml_benches: Option<&Vec<TomlBenchTarget>>,
537    package_root: &Path,
538    edition: Edition,
539    autodiscover: Option<bool>,
540    warnings: &mut Vec<String>,
541    errors: &mut Vec<String>,
542) -> CargoResult<Vec<TomlBenchTarget>> {
543    let mut legacy_warnings = vec![];
544    let mut legacy_bench_path = |bench: &TomlTarget| {
545        let legacy_path = Path::new("src").join("bench.rs");
546        if !(name_or_panic(bench) == "bench" && package_root.join(&legacy_path).exists()) {
547            return None;
548        }
549        legacy_warnings.push(format!(
550            "path `{}` was erroneously implicitly accepted for benchmark `{}`,\n\
551                 please set bench.path in Cargo.toml",
552            legacy_path.display(),
553            name_or_panic(bench)
554        ));
555        Some(legacy_path)
556    };
557
558    let mut inferred = || infer_from_directory(&package_root, Path::new(DEFAULT_BENCH_DIR_NAME));
559
560    let targets = normalize_targets_with_legacy_path(
561        TARGET_KIND_HUMAN_BENCH,
562        TARGET_KIND_BENCH,
563        toml_benches,
564        &mut inferred,
565        package_root,
566        edition,
567        autodiscover,
568        warnings,
569        errors,
570        &mut legacy_bench_path,
571        "autobenches",
572    )?;
573    warnings.append(&mut legacy_warnings);
574
575    Ok(targets)
576}
577
578#[tracing::instrument(skip_all)]
579fn to_bench_targets(
580    targets: &[TomlBenchTarget],
581    package_root: &Path,
582    edition: Edition,
583    warnings: &mut Vec<String>,
584) -> CargoResult<Vec<Target>> {
585    validate_unique_names(&targets, TARGET_KIND_BENCH)?;
586
587    let mut result = Vec::with_capacity(targets.len());
588    for toml in targets {
589        let path = package_root.join(&toml.path.as_ref().expect("previously normalized").0);
590        let mut target = Target::bench_target(
591            name_or_panic(&toml),
592            path,
593            toml.required_features.clone(),
594            edition,
595        );
596        configure(&toml, &mut target, TARGET_KIND_HUMAN_BENCH, warnings)?;
597        result.push(target);
598    }
599
600    Ok(result)
601}
602
603fn is_normalized(toml_target: Option<&TomlTarget>, autodiscover: Option<bool>) -> bool {
604    are_normalized_(toml_target.map(std::slice::from_ref), autodiscover)
605}
606
607fn are_normalized(toml_targets: Option<&Vec<TomlTarget>>, autodiscover: Option<bool>) -> bool {
608    are_normalized_(toml_targets.map(|v| v.as_slice()), autodiscover)
609}
610
611fn are_normalized_(toml_targets: Option<&[TomlTarget]>, autodiscover: Option<bool>) -> bool {
612    if autodiscover != Some(false) {
613        return false;
614    }
615
616    let Some(toml_targets) = toml_targets else {
617        return true;
618    };
619    toml_targets
620        .iter()
621        .all(|t| t.name.is_some() && t.path.is_some())
622}
623
624fn normalize_targets(
625    target_kind_human: &str,
626    target_kind: &str,
627    toml_targets: Option<&Vec<TomlTarget>>,
628    inferred: &mut dyn FnMut() -> Vec<(String, PathBuf)>,
629    package_root: &Path,
630    edition: Edition,
631    autodiscover: Option<bool>,
632    warnings: &mut Vec<String>,
633    errors: &mut Vec<String>,
634    autodiscover_flag_name: &str,
635) -> CargoResult<Vec<TomlTarget>> {
636    normalize_targets_with_legacy_path(
637        target_kind_human,
638        target_kind,
639        toml_targets,
640        inferred,
641        package_root,
642        edition,
643        autodiscover,
644        warnings,
645        errors,
646        &mut |_| None,
647        autodiscover_flag_name,
648    )
649}
650
651fn normalize_targets_with_legacy_path(
652    target_kind_human: &str,
653    target_kind: &str,
654    toml_targets: Option<&Vec<TomlTarget>>,
655    inferred: &mut dyn FnMut() -> Vec<(String, PathBuf)>,
656    package_root: &Path,
657    edition: Edition,
658    autodiscover: Option<bool>,
659    warnings: &mut Vec<String>,
660    errors: &mut Vec<String>,
661    legacy_path: &mut dyn FnMut(&TomlTarget) -> Option<PathBuf>,
662    autodiscover_flag_name: &str,
663) -> CargoResult<Vec<TomlTarget>> {
664    if are_normalized(toml_targets, autodiscover) {
665        let mut toml_targets = toml_targets.cloned().unwrap_or_default();
666        for target in toml_targets.iter_mut() {
667            // Check early to improve error messages
668            validate_target_name(target, target_kind_human, target_kind, warnings)?;
669
670            validate_proc_macro(target, target_kind_human, edition, warnings)?;
671            validate_crate_types(target, target_kind_human, edition, warnings)?;
672
673            if let Some(PathValue(path)) = &target.path {
674                target.path = Some(PathValue(paths::normalize_path(path).into()));
675            }
676        }
677        Ok(toml_targets)
678    } else {
679        let inferred = inferred();
680        let toml_targets = toml_targets_and_inferred(
681            toml_targets,
682            &inferred,
683            package_root,
684            autodiscover,
685            edition,
686            warnings,
687            target_kind_human,
688            target_kind,
689            autodiscover_flag_name,
690        );
691
692        for target in &toml_targets {
693            // Check early to improve error messages
694            validate_target_name(target, target_kind_human, target_kind, warnings)?;
695
696            validate_proc_macro(target, target_kind_human, edition, warnings)?;
697            validate_crate_types(target, target_kind_human, edition, warnings)?;
698        }
699
700        let mut result = Vec::new();
701        for mut target in toml_targets {
702            let path = target_path(
703                &target,
704                &inferred,
705                target_kind,
706                package_root,
707                edition,
708                legacy_path,
709            );
710            let path = match path {
711                Ok(path) => path,
712                Err(e) => {
713                    errors.push(e);
714                    continue;
715                }
716            };
717            target.path = Some(PathValue(paths::normalize_path(&path).into()));
718            result.push(target);
719        }
720        Ok(result)
721    }
722}
723
724fn inferred_lib(package_root: &Path) -> Option<PathBuf> {
725    let lib = Path::new("src").join("lib.rs");
726    if package_root.join(&lib).exists() {
727        Some(lib)
728    } else {
729        None
730    }
731}
732
733fn inferred_bins(package_root: &Path, package_name: &str) -> Vec<(String, PathBuf)> {
734    let main = "src/main.rs";
735    let mut result = Vec::new();
736    if package_root.join(main).exists() {
737        let main = PathBuf::from(main);
738        result.push((package_name.to_string(), main));
739    }
740    let default_bin_dir_name = Path::new("src").join("bin");
741    result.extend(infer_from_directory(package_root, &default_bin_dir_name));
742
743    result
744}
745
746fn infer_from_directory(package_root: &Path, relpath: &Path) -> Vec<(String, PathBuf)> {
747    let directory = package_root.join(relpath);
748    let entries = match fs::read_dir(directory) {
749        Err(_) => return Vec::new(),
750        Ok(dir) => dir,
751    };
752
753    entries
754        .filter_map(|e| e.ok())
755        .filter(is_not_dotfile)
756        .filter_map(|d| infer_any(package_root, &d))
757        .collect()
758}
759
760fn infer_any(package_root: &Path, entry: &DirEntry) -> Option<(String, PathBuf)> {
761    if entry.file_type().map_or(false, |t| t.is_dir()) {
762        infer_subdirectory(package_root, entry)
763    } else if entry.path().extension().and_then(|p| p.to_str()) == Some("rs") {
764        infer_file(package_root, entry)
765    } else {
766        None
767    }
768}
769
770fn infer_file(package_root: &Path, entry: &DirEntry) -> Option<(String, PathBuf)> {
771    let path = entry.path();
772    let stem = path.file_stem()?.to_str()?.to_owned();
773    let path = path
774        .strip_prefix(package_root)
775        .map(|p| p.to_owned())
776        .unwrap_or(path);
777    Some((stem, path))
778}
779
780fn infer_subdirectory(package_root: &Path, entry: &DirEntry) -> Option<(String, PathBuf)> {
781    let path = entry.path();
782    let main = path.join("main.rs");
783    let name = path.file_name()?.to_str()?.to_owned();
784    if main.exists() {
785        let main = main
786            .strip_prefix(package_root)
787            .map(|p| p.to_owned())
788            .unwrap_or(main);
789        Some((name, main))
790    } else {
791        None
792    }
793}
794
795fn is_not_dotfile(entry: &DirEntry) -> bool {
796    entry.file_name().to_str().map(|s| s.starts_with('.')) == Some(false)
797}
798
799fn toml_targets_and_inferred(
800    toml_targets: Option<&Vec<TomlTarget>>,
801    inferred: &[(String, PathBuf)],
802    package_root: &Path,
803    autodiscover: Option<bool>,
804    edition: Edition,
805    warnings: &mut Vec<String>,
806    target_kind_human: &str,
807    target_kind: &str,
808    autodiscover_flag_name: &str,
809) -> Vec<TomlTarget> {
810    let inferred_targets = inferred_to_toml_targets(inferred);
811    let mut toml_targets = match toml_targets {
812        None => {
813            if let Some(false) = autodiscover {
814                vec![]
815            } else {
816                inferred_targets
817            }
818        }
819        Some(targets) => {
820            let mut targets = targets.clone();
821
822            let target_path =
823                |target: &TomlTarget| target.path.clone().map(|p| package_root.join(p.0));
824
825            let mut seen_names = HashSet::default();
826            let mut seen_paths = HashSet::default();
827            for target in targets.iter() {
828                seen_names.insert(target.name.clone());
829                seen_paths.insert(target_path(target));
830            }
831
832            let mut rem_targets = vec![];
833            for target in inferred_targets {
834                if !seen_names.contains(&target.name) && !seen_paths.contains(&target_path(&target))
835                {
836                    rem_targets.push(target);
837                }
838            }
839
840            let autodiscover = match autodiscover {
841                Some(autodiscover) => autodiscover,
842                None => {
843                    if edition == Edition::Edition2015 {
844                        if !rem_targets.is_empty() {
845                            let mut rem_targets_str = String::new();
846                            for t in rem_targets.iter() {
847                                if let Some(p) = t.path.clone() {
848                                    rem_targets_str.push_str(&format!("* {}\n", p.0.display()))
849                                }
850                            }
851                            warnings.push(format!(
852                                "\
853An explicit [[{section}]] section is specified in Cargo.toml which currently
854disables Cargo from automatically inferring other {target_kind_human} targets.
855This inference behavior will change in the Rust 2018 edition and the following
856files will be included as a {target_kind_human} target:
857
858{rem_targets_str}
859This is likely to break cargo build or cargo test as these files may not be
860ready to be compiled as a {target_kind_human} target today. You can future-proof yourself
861and disable this warning by adding `{autodiscover_flag_name} = false` to your [package]
862section. You may also move the files to a location where Cargo would not
863automatically infer them to be a target, such as in subfolders.
864
865For more information on this warning you can consult
866https://github.com/rust-lang/cargo/issues/5330",
867                                section = target_kind,
868                                target_kind_human = target_kind_human,
869                                rem_targets_str = rem_targets_str,
870                                autodiscover_flag_name = autodiscover_flag_name,
871                            ));
872                        };
873                        false
874                    } else {
875                        true
876                    }
877                }
878            };
879
880            if autodiscover {
881                targets.append(&mut rem_targets);
882            }
883
884            targets
885        }
886    };
887    // Ensure target order is deterministic, particularly for `cargo vendor` where re-vendoring
888    // should not cause changes.
889    //
890    // `unstable` should be deterministic because we enforce that `t.name` is unique
891    toml_targets.sort_unstable_by_key(|t| t.name.clone());
892    toml_targets
893}
894
895fn inferred_to_toml_targets(inferred: &[(String, PathBuf)]) -> Vec<TomlTarget> {
896    inferred
897        .iter()
898        .map(|(name, path)| TomlTarget {
899            name: Some(name.clone()),
900            path: Some(PathValue(path.clone())),
901            ..TomlTarget::new()
902        })
903        .collect()
904}
905
906/// Will check a list of toml targets, and make sure the target names are unique within a vector.
907fn validate_unique_names(targets: &[TomlTarget], target_kind: &str) -> CargoResult<()> {
908    let mut seen = HashSet::default();
909    for name in targets.iter().map(|e| name_or_panic(e)) {
910        if !seen.insert(name) {
911            anyhow::bail!(
912                "found duplicate {target_kind} name {name}, \
913                 but all {target_kind} targets must have a unique name",
914                target_kind = target_kind,
915                name = name
916            );
917        }
918    }
919    Ok(())
920}
921
922/// Will check a list of build scripts, and make sure script file stems are unique within a vector.
923fn validate_unique_build_scripts(scripts: &[String]) -> CargoResult<()> {
924    let mut seen = HashMap::default();
925    for script in scripts {
926        let stem = Path::new(script)
927            .file_stem()
928            .and_then(|s| s.to_str())
929            .expect("previously normalized");
930        seen.entry(stem)
931            .or_insert_with(Vec::new)
932            .push(script.as_str());
933    }
934    let mut conflict_file_stem = false;
935    let mut err_msg = String::from(
936        "found build scripts with duplicate file stems, but all build scripts must have a unique file stem",
937    );
938    for (stem, paths) in seen {
939        if paths.len() > 1 {
940            conflict_file_stem = true;
941            write!(&mut err_msg, "\n  for stem `{stem}`: {}", paths.join(", "))?;
942        }
943    }
944    if conflict_file_stem {
945        anyhow::bail!(err_msg);
946    }
947    Ok(())
948}
949
950fn configure(
951    toml: &TomlTarget,
952    target: &mut Target,
953    target_kind_human: &str,
954    warnings: &mut Vec<String>,
955) -> CargoResult<()> {
956    let t2 = target.clone();
957    target
958        .set_tested(toml.test.unwrap_or_else(|| t2.tested()))
959        .set_doc(toml.doc.unwrap_or_else(|| t2.documented()))
960        .set_doctest(toml.doctest.unwrap_or_else(|| t2.doctested()))
961        .set_benched(toml.bench.unwrap_or_else(|| t2.benched()))
962        .set_harness(toml.harness.unwrap_or_else(|| t2.harness()))
963        .set_proc_macro(toml.proc_macro().unwrap_or_else(|| t2.proc_macro()))
964        .set_doc_scrape_examples(match toml.doc_scrape_examples {
965            None => RustdocScrapeExamples::Unset,
966            Some(false) => RustdocScrapeExamples::Disabled,
967            Some(true) => RustdocScrapeExamples::Enabled,
968        })
969        .set_for_host(toml.proc_macro().unwrap_or_else(|| t2.for_host()));
970
971    if let Some(edition) = toml.edition.clone() {
972        let name = target.name();
973        warnings.push(format!(
974            "`edition` is set on {target_kind_human} `{name}` which is deprecated"
975        ));
976        target.set_edition(
977            edition
978                .parse()
979                .context("failed to parse the `edition` key")?,
980        );
981    }
982    Ok(())
983}
984
985/// Build an error message for a target path that cannot be determined either
986/// by auto-discovery or specifying.
987///
988/// This function tries to detect commonly wrong paths for targets:
989///
990/// test -> tests/*.rs, tests/*/main.rs
991/// bench -> benches/*.rs, benches/*/main.rs
992/// example -> examples/*.rs, examples/*/main.rs
993/// bin -> src/bin/*.rs, src/bin/*/main.rs
994///
995/// Note that the logic need to sync with [`infer_from_directory`] if changes.
996fn target_path_not_found_error_message(
997    package_root: &Path,
998    target: &TomlTarget,
999    target_kind: &str,
1000    inferred: &[(String, PathBuf)],
1001) -> String {
1002    fn possible_target_paths(name: &str, kind: &str, commonly_wrong: bool) -> [PathBuf; 2] {
1003        let mut target_path = PathBuf::new();
1004        match (kind, commonly_wrong) {
1005            // commonly wrong paths
1006            ("test" | "bench" | "example", true) => target_path.push(kind),
1007            ("bin", true) => target_path.extend(["src", "bins"]),
1008            // default inferred paths
1009            ("test", false) => target_path.push(DEFAULT_TEST_DIR_NAME),
1010            ("bench", false) => target_path.push(DEFAULT_BENCH_DIR_NAME),
1011            ("example", false) => target_path.push(DEFAULT_EXAMPLE_DIR_NAME),
1012            ("bin", false) => target_path.extend(["src", "bin"]),
1013            _ => unreachable!("invalid target kind: {}", kind),
1014        }
1015
1016        let target_path_file = {
1017            let mut path = target_path.clone();
1018            path.push(format!("{name}.rs"));
1019            path
1020        };
1021        let target_path_subdir = {
1022            target_path.extend([name, "main.rs"]);
1023            target_path
1024        };
1025        return [target_path_file, target_path_subdir];
1026    }
1027
1028    let target_name = name_or_panic(target);
1029
1030    let commonly_wrong_paths = possible_target_paths(&target_name, target_kind, true);
1031    let possible_paths = possible_target_paths(&target_name, target_kind, false);
1032
1033    let msg = closest_msg(target_name, inferred.iter(), |(n, _p)| n, target_kind);
1034    if let Some((wrong_path, possible_path)) = commonly_wrong_paths
1035        .iter()
1036        .zip(possible_paths.iter())
1037        .filter(|(wp, _)| package_root.join(wp).exists())
1038        .next()
1039    {
1040        let [wrong_path, possible_path] = [wrong_path, possible_path].map(|p| p.display());
1041        format!(
1042            "can't find `{target_name}` {target_kind} at default paths, but found a file at `{wrong_path}`.\n\
1043             Perhaps rename the file to `{possible_path}` for target auto-discovery, \
1044             or specify {target_kind}.path if you want to use a non-default path.{msg}",
1045        )
1046    } else {
1047        let [path_file, path_dir] = possible_paths.each_ref().map(|p| p.display());
1048        format!(
1049            "can't find `{target_name}` {target_kind} at `{path_file}` or `{path_dir}`. \
1050             Please specify {target_kind}.path if you want to use a non-default path.{msg}"
1051        )
1052    }
1053}
1054
1055fn target_path(
1056    target: &TomlTarget,
1057    inferred: &[(String, PathBuf)],
1058    target_kind: &str,
1059    package_root: &Path,
1060    edition: Edition,
1061    legacy_path: &mut dyn FnMut(&TomlTarget) -> Option<PathBuf>,
1062) -> Result<PathBuf, String> {
1063    if let Some(ref path) = target.path {
1064        // Should we verify that this path exists here?
1065        return Ok(path.0.clone());
1066    }
1067    let name = name_or_panic(target).to_owned();
1068
1069    let mut matching = inferred
1070        .iter()
1071        .filter(|(n, _)| n == &name)
1072        .map(|(_, p)| p.clone());
1073
1074    let first = matching.next();
1075    let second = matching.next();
1076    match (first, second) {
1077        (Some(path), None) => Ok(path),
1078        (None, None) => {
1079            if edition == Edition::Edition2015 {
1080                if let Some(path) = legacy_path(target) {
1081                    return Ok(path);
1082                }
1083            }
1084            Err(target_path_not_found_error_message(
1085                package_root,
1086                target,
1087                target_kind,
1088                inferred,
1089            ))
1090        }
1091        (Some(p0), Some(p1)) => {
1092            if edition == Edition::Edition2015 {
1093                if let Some(path) = legacy_path(target) {
1094                    return Ok(path);
1095                }
1096            }
1097            Err(format!(
1098                "\
1099cannot infer path for `{}` {}
1100Cargo doesn't know which to use because multiple target files found at `{}` and `{}`.",
1101                name_or_panic(target),
1102                target_kind,
1103                p0.strip_prefix(package_root).unwrap_or(&p0).display(),
1104                p1.strip_prefix(package_root).unwrap_or(&p1).display(),
1105            ))
1106        }
1107        (None, Some(_)) => unreachable!(),
1108    }
1109}
1110
1111/// Returns the path to the build script if one exists for this crate.
1112#[tracing::instrument(skip_all)]
1113pub fn normalize_build(
1114    build: Option<&TomlPackageBuild>,
1115    package_root: &Path,
1116) -> CargoResult<Option<TomlPackageBuild>> {
1117    const BUILD_RS: &str = "build.rs";
1118    match build {
1119        None => {
1120            // If there is a `build.rs` file next to the `Cargo.toml`, assume it is
1121            // a build script.
1122            let build_rs = package_root.join(BUILD_RS);
1123            if build_rs.is_file() {
1124                Ok(Some(TomlPackageBuild::SingleScript(BUILD_RS.to_owned())))
1125            } else {
1126                Ok(Some(TomlPackageBuild::Auto(false)))
1127            }
1128        }
1129        // Explicitly no build script.
1130        Some(TomlPackageBuild::Auto(false)) => Ok(build.cloned()),
1131        Some(TomlPackageBuild::SingleScript(build_file)) => {
1132            validate_build_name(build_file)?;
1133            let build_file = paths::normalize_path(Path::new(build_file));
1134            let build = build_file.into_os_string().into_string().expect(
1135                "`build_file` started as a String and `normalize_path` shouldn't have changed that",
1136            );
1137            Ok(Some(TomlPackageBuild::SingleScript(build)))
1138        }
1139        Some(TomlPackageBuild::Auto(true)) => {
1140            Ok(Some(TomlPackageBuild::SingleScript(BUILD_RS.to_owned())))
1141        }
1142        Some(TomlPackageBuild::MultipleScript(scripts)) => {
1143            for script in scripts {
1144                validate_build_name(script)?;
1145            }
1146            Ok(build.cloned())
1147        }
1148    }
1149}
1150
1151fn validate_build_name(build: &str) -> CargoResult<()> {
1152    if Path::new(build).file_stem().is_none() {
1153        anyhow::bail!("invalid `package.build` file name");
1154    }
1155    Ok(())
1156}
1157
1158fn name_or_panic(target: &TomlTarget) -> &str {
1159    target
1160        .name
1161        .as_deref()
1162        .unwrap_or_else(|| panic!("target name is required"))
1163}
1164
1165fn validate_lib_name(target: &TomlTarget, warnings: &mut Vec<String>) -> CargoResult<()> {
1166    validate_target_name(target, TARGET_KIND_HUMAN_LIB, TARGET_KIND_LIB, warnings)?;
1167    let name = name_or_panic(target);
1168    if name.contains('-') {
1169        anyhow::bail!("library target names cannot contain hyphens: {}", name)
1170    }
1171
1172    Ok(())
1173}
1174
1175fn validate_bin_name(bin: &TomlTarget, warnings: &mut Vec<String>) -> CargoResult<()> {
1176    validate_target_name(bin, TARGET_KIND_HUMAN_BIN, TARGET_KIND_BIN, warnings)?;
1177    let name = name_or_panic(bin).to_owned();
1178    if restricted_names::is_conflicting_artifact_name(&name) {
1179        anyhow::bail!(
1180            "the binary target name `{name}` is forbidden, \
1181                 it conflicts with cargo's build directory names",
1182        )
1183    }
1184
1185    Ok(())
1186}
1187
1188fn validate_target_name(
1189    target: &TomlTarget,
1190    target_kind_human: &str,
1191    target_kind: &str,
1192    warnings: &mut Vec<String>,
1193) -> CargoResult<()> {
1194    match target.name {
1195        Some(ref name) => {
1196            if name.trim().is_empty() {
1197                anyhow::bail!("{} target names cannot be empty", target_kind_human)
1198            }
1199            if cfg!(windows) && restricted_names::is_windows_reserved(name) {
1200                warnings.push(format!(
1201                    "{} target `{}` is a reserved Windows filename, \
1202                        this target will not work on Windows platforms",
1203                    target_kind_human, name
1204                ));
1205            }
1206        }
1207        None => anyhow::bail!(
1208            "{} target {}.name is required",
1209            target_kind_human,
1210            target_kind
1211        ),
1212    }
1213
1214    Ok(())
1215}
1216
1217fn validate_bin_proc_macro(
1218    target: &TomlTarget,
1219    edition: Edition,
1220    warnings: &mut Vec<String>,
1221    errors: &mut Vec<String>,
1222) -> CargoResult<()> {
1223    if target.proc_macro() == Some(true) {
1224        let name = name_or_panic(target);
1225        errors.push(format!(
1226            "the target `{}` is a binary and can't have `proc-macro` \
1227                 set `true`",
1228            name
1229        ));
1230    } else {
1231        validate_proc_macro(target, TARGET_KIND_HUMAN_BIN, edition, warnings)?;
1232    }
1233    Ok(())
1234}
1235
1236fn validate_proc_macro(
1237    target: &TomlTarget,
1238    kind: &str,
1239    edition: Edition,
1240    warnings: &mut Vec<String>,
1241) -> CargoResult<()> {
1242    deprecated_underscore(
1243        &target.proc_macro2,
1244        &target.proc_macro,
1245        "proc-macro",
1246        name_or_panic(target),
1247        format!("{kind} target").as_str(),
1248        edition,
1249        warnings,
1250    )
1251}
1252
1253fn validate_bin_crate_types(
1254    target: &TomlTarget,
1255    edition: Edition,
1256    warnings: &mut Vec<String>,
1257    errors: &mut Vec<String>,
1258) -> CargoResult<()> {
1259    if let Some(crate_types) = target.crate_types() {
1260        if !crate_types.is_empty() {
1261            let name = name_or_panic(target);
1262            errors.push(format!(
1263                "the target `{}` is a binary and can't have any \
1264                     crate-types set (currently \"{}\")",
1265                name,
1266                crate_types.join(", ")
1267            ));
1268        } else {
1269            validate_crate_types(target, TARGET_KIND_HUMAN_BIN, edition, warnings)?;
1270        }
1271    }
1272    Ok(())
1273}
1274
1275fn validate_crate_types(
1276    target: &TomlTarget,
1277    kind: &str,
1278    edition: Edition,
1279    warnings: &mut Vec<String>,
1280) -> CargoResult<()> {
1281    deprecated_underscore(
1282        &target.crate_type2,
1283        &target.crate_type,
1284        "crate-type",
1285        name_or_panic(target),
1286        format!("{kind} target").as_str(),
1287        edition,
1288        warnings,
1289    )
1290}