Files
addr2line
adler
aho_corasick
ansi_term
atty
backtrace
base64
bincode
bitflags
bitmaps
bstr
byteorder
bytes
bytesize
cargo
cargo_platform
cfg_if
chrono
clap
color_backtrace
corpus_database
corpus_database_dsl
corpus_extractor
corpus_manager
corpus_manager_driver
corpus_queries_derive
corpus_queries_impl
crates_index
crates_io
crc32fast
crossbeam_queue
crossbeam_utils
crypto_hash
csv
csv_core
curl
curl_sys
darling
darling_core
darling_macro
datafrog
datapond
datapond_derive
datapond_macro
either
encoding_rs
env_logger
error_chain
failure
failure_derive
filetime
flate2
fnv
foreign_types
foreign_types_shared
form_urlencoded
fs2
futures
futures_channel
futures_core
futures_io
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
stream
task
getrandom
gimli
git2
git2_curl
glob
globset
h2
hashbrown
heck
hex
home
http
http_body
httparse
httpdate
humantime
hyper
hyper_tls
ident_case
idna
ignore
im_rc
indexmap
iovec
ipnet
itertools
itoa
jobserver
lazy_static
lazycell
libc
libgit2_sys
libnghttp2_sys
libssh2_sys
libz_sys
lock_api
log
log_derive
matches
maybe_uninit
memchr
mime
miniz_oxide
mio
mio_uds
native_tls
nix
num_cpus
num_integer
num_traits
object
once_cell
opener
openssl
openssl_probe
openssl_sys
parking_lot
parking_lot_core
percent_encoding
pest
pin_project
pin_project_lite
pin_utils
ppv_lite86
print_stats
proc_macro2
proc_macro_error
proc_macro_error_attr
proc_macro_hack
proc_macro_nested
quick_error
quote
rand
rand_chacha
rand_core
rand_xoshiro
regex
regex_automata
regex_syntax
remove_dir_all
reqwest
rustc
rustc_demangle
rustc_hash
rustc_workspace_hack
rustfix
rustwide
ryu
same_file
scopeguard
semver
semver_parser
serde
serde_derive
serde_ignored
serde_json
serde_urlencoded
shell_escape
signal_hook_registry
simplelog
sized_chunks
slab
smallvec
socket2
strip_ansi_escapes
strsim
structopt
structopt_derive
syn
synstructure
tar
tempdir
tempfile
termcolor
textwrap
thiserror
thiserror_impl
thread_local
time
tinyvec
tinyvec_macros
tokio
future
io
loom
macros
net
park
runtime
sync
task
time
util
tokio_executor
tokio_io
tokio_native_tls
tokio_process
tokio_reactor
tokio_signal
tokio_stream
tokio_sync
tokio_util
toml
tower_service
tracing
tracing_core
tracing_futures
try_lock
typenum
ucd_trie
unicode_bidi
unicode_normalization
unicode_segmentation
unicode_width
unicode_xid
url
utf8parse
vec_map
vte
walkdir
want
xattr
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
//! This module implements Cargo conventions for directory layout:
//!
//!  * `src/lib.rs` is a library
//!  * `src/main.rs` is a binary
//!  * `src/bin/*.rs` are binaries
//!  * `examples/*.rs` are examples
//!  * `tests/*.rs` are integration tests
//!  * `benches/*.rs` are benchmarks
//!
//! It is a bit tricky because we need match explicit information from `Cargo.toml`
//! with implicit info in directory layout.

use std::collections::HashSet;
use std::fs::{self, DirEntry};
use std::path::{Path, PathBuf};

use super::{
    LibKind, PathValue, StringOrBool, StringOrVec, TomlBenchTarget, TomlBinTarget,
    TomlExampleTarget, TomlLibTarget, TomlManifest, TomlTarget, TomlTestTarget,
};
use crate::core::{compiler, Edition, Feature, Features, Target};
use crate::util::errors::{CargoResult, CargoResultExt};

pub fn targets(
    features: &Features,
    manifest: &TomlManifest,
    package_name: &str,
    package_root: &Path,
    edition: Edition,
    custom_build: &Option<StringOrBool>,
    metabuild: &Option<StringOrVec>,
    warnings: &mut Vec<String>,
    errors: &mut Vec<String>,
) -> CargoResult<Vec<Target>> {
    let mut targets = Vec::new();

    let has_lib;

    if let Some(target) = clean_lib(
        features,
        manifest.lib.as_ref(),
        package_root,
        package_name,
        edition,
        warnings,
    )? {
        targets.push(target);
        has_lib = true;
    } else {
        has_lib = false;
    }

    let package = manifest
        .package
        .as_ref()
        .or_else(|| manifest.project.as_ref())
        .ok_or_else(|| failure::format_err!("manifest has no `package` (or `project`)"))?;

    targets.extend(clean_bins(
        features,
        manifest.bin.as_ref(),
        package_root,
        package_name,
        edition,
        package.autobins,
        warnings,
        errors,
        has_lib,
    )?);

    targets.extend(clean_examples(
        features,
        manifest.example.as_ref(),
        package_root,
        edition,
        package.autoexamples,
        warnings,
        errors,
    )?);

    targets.extend(clean_tests(
        features,
        manifest.test.as_ref(),
        package_root,
        edition,
        package.autotests,
        warnings,
        errors,
    )?);

    targets.extend(clean_benches(
        features,
        manifest.bench.as_ref(),
        package_root,
        edition,
        package.autobenches,
        warnings,
        errors,
    )?);

    // processing the custom build script
    if let Some(custom_build) = manifest.maybe_custom_build(custom_build, package_root) {
        if metabuild.is_some() {
            failure::bail!("cannot specify both `metabuild` and `build`");
        }
        let name = format!(
            "build-script-{}",
            custom_build
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("")
        );
        targets.push(Target::custom_build_target(
            &name,
            package_root.join(custom_build),
            edition,
        ));
    }
    if let Some(metabuild) = metabuild {
        // Verify names match available build deps.
        let bdeps = manifest.build_dependencies.as_ref();
        for name in &metabuild.0 {
            if !bdeps.map_or(false, |bd| bd.contains_key(name)) {
                failure::bail!(
                    "metabuild package `{}` must be specified in `build-dependencies`",
                    name
                );
            }
        }

        targets.push(Target::metabuild_target(&format!(
            "metabuild-{}",
            package.name
        )));
    }

    Ok(targets)
}

fn clean_lib(
    features: &Features,
    toml_lib: Option<&TomlLibTarget>,
    package_root: &Path,
    package_name: &str,
    edition: Edition,
    warnings: &mut Vec<String>,
) -> CargoResult<Option<Target>> {
    let inferred = inferred_lib(package_root);
    let lib = match toml_lib {
        Some(lib) => {
            if let Some(ref name) = lib.name {
                // XXX: other code paths dodge this validation
                if name.contains('-') {
                    failure::bail!("library target names cannot contain hyphens: {}", name)
                }
            }
            Some(TomlTarget {
                name: lib.name.clone().or_else(|| Some(package_name.to_owned())),
                ..lib.clone()
            })
        }
        None => inferred.as_ref().map(|lib| TomlTarget {
            name: Some(package_name.to_string()),
            path: Some(PathValue(lib.clone())),
            ..TomlTarget::new()
        }),
    };

    let lib = match lib {
        Some(ref lib) => lib,
        None => return Ok(None),
    };

    validate_has_name(lib, "library", "lib")?;

    let path = match (lib.path.as_ref(), inferred) {
        (Some(path), _) => package_root.join(&path.0),
        (None, Some(path)) => path,
        (None, None) => {
            let legacy_path = package_root.join("src").join(format!("{}.rs", lib.name()));
            if edition == Edition::Edition2015 && legacy_path.exists() {
                warnings.push(format!(
                    "path `{}` was erroneously implicitly accepted for library `{}`,\n\
                     please rename the file to `src/lib.rs` or set lib.path in Cargo.toml",
                    legacy_path.display(),
                    lib.name()
                ));
                legacy_path
            } else {
                failure::bail!(
                    "can't find library `{}`, \
                     rename file to `src/lib.rs` or specify lib.path",
                    lib.name()
                )
            }
        }
    };

    // Per the Macros 1.1 RFC:
    //
    // > Initially if a crate is compiled with the `proc-macro` crate type
    // > (and possibly others) it will forbid exporting any items in the
    // > crate other than those functions tagged #[proc_macro_derive] and
    // > those functions must also be placed at the crate root.
    //
    // A plugin requires exporting plugin_registrar so a crate cannot be
    // both at once.
    let crate_types = match (lib.crate_types(), lib.plugin, lib.proc_macro()) {
        (Some(kinds), _, _) if kinds.contains(&"proc-macro".to_string()) => {
            if let Some(true) = lib.plugin {
                // This is a warning to retain backwards compatibility.
                warnings.push(format!(
                    "proc-macro library `{}` should not specify `plugin = true`",
                    lib.name()
                ));
            }
            warnings.push(format!(
                "library `{}` should only specify `proc-macro = true` instead of setting `crate-type`",
                lib.name()
            ));
            if kinds.len() > 1 {
                failure::bail!("cannot mix `proc-macro` crate type with others");
            }
            vec![LibKind::ProcMacro]
        }
        (_, Some(true), Some(true)) => {
            failure::bail!("`lib.plugin` and `lib.proc-macro` cannot both be `true`")
        }
        (Some(kinds), _, _) => kinds.iter().map(|s| s.into()).collect(),
        (None, Some(true), _) => vec![LibKind::Dylib],
        (None, _, Some(true)) => vec![LibKind::ProcMacro],
        (None, _, _) => vec![LibKind::Lib],
    };

    let mut target = Target::lib_target(&lib.name(), crate_types, path, edition);
    configure(features, lib, &mut target)?;
    Ok(Some(target))
}

fn clean_bins(
    features: &Features,
    toml_bins: Option<&Vec<TomlBinTarget>>,
    package_root: &Path,
    package_name: &str,
    edition: Edition,
    autodiscover: Option<bool>,
    warnings: &mut Vec<String>,
    errors: &mut Vec<String>,
    has_lib: bool,
) -> CargoResult<Vec<Target>> {
    let inferred = inferred_bins(package_root, package_name);

    let bins = toml_targets_and_inferred(
        toml_bins,
        &inferred,
        package_root,
        autodiscover,
        edition,
        warnings,
        "binary",
        "bin",
        "autobins",
    );

    for bin in &bins {
        validate_has_name(bin, "binary", "bin")?;

        let name = bin.name();

        if let Some(crate_types) = bin.crate_types() {
            if !crate_types.is_empty() {
                errors.push(format!(
                    "the target `{}` is a binary and can't have any \
                     crate-types set (currently \"{}\")",
                    name,
                    crate_types.join(", ")
                ));
            }
        }

        if bin.proc_macro() == Some(true) {
            errors.push(format!(
                "the target `{}` is a binary and can't have `proc-macro` \
                 set `true`",
                name
            ));
        }

        if compiler::is_bad_artifact_name(&name) {
            failure::bail!("the binary target name `{}` is forbidden", name)
        }
    }

    validate_unique_names(&bins, "binary")?;

    let mut result = Vec::new();
    for bin in &bins {
        let path = target_path(bin, &inferred, "bin", package_root, edition, &mut |_| {
            if let Some(legacy_path) = legacy_bin_path(package_root, &bin.name(), has_lib) {
                warnings.push(format!(
                    "path `{}` was erroneously implicitly accepted for binary `{}`,\n\
                     please set bin.path in Cargo.toml",
                    legacy_path.display(),
                    bin.name()
                ));
                Some(legacy_path)
            } else {
                None
            }
        });
        let path = match path {
            Ok(path) => path,
            Err(e) => failure::bail!("{}", e),
        };

        let mut target =
            Target::bin_target(&bin.name(), path, bin.required_features.clone(), edition);
        configure(features, bin, &mut target)?;
        result.push(target);
    }
    return Ok(result);

    fn legacy_bin_path(package_root: &Path, name: &str, has_lib: bool) -> Option<PathBuf> {
        if !has_lib {
            let path = package_root.join("src").join(format!("{}.rs", name));
            if path.exists() {
                return Some(path);
            }
        }
        let path = package_root.join("src").join("main.rs");
        if path.exists() {
            return Some(path);
        }

        let path = package_root.join("src").join("bin").join("main.rs");
        if path.exists() {
            return Some(path);
        }
        None
    }
}

fn clean_examples(
    features: &Features,
    toml_examples: Option<&Vec<TomlExampleTarget>>,
    package_root: &Path,
    edition: Edition,
    autodiscover: Option<bool>,
    warnings: &mut Vec<String>,
    errors: &mut Vec<String>,
) -> CargoResult<Vec<Target>> {
    let inferred = infer_from_directory(&package_root.join("examples"));

    let targets = clean_targets(
        "example",
        "example",
        toml_examples,
        &inferred,
        package_root,
        edition,
        autodiscover,
        warnings,
        errors,
        "autoexamples",
    )?;

    let mut result = Vec::new();
    for (path, toml) in targets {
        let crate_types = match toml.crate_types() {
            Some(kinds) => kinds.iter().map(|s| s.into()).collect(),
            None => Vec::new(),
        };

        let mut target = Target::example_target(
            &toml.name(),
            crate_types,
            path,
            toml.required_features.clone(),
            edition,
        );
        configure(features, &toml, &mut target)?;
        result.push(target);
    }

    Ok(result)
}

fn clean_tests(
    features: &Features,
    toml_tests: Option<&Vec<TomlTestTarget>>,
    package_root: &Path,
    edition: Edition,
    autodiscover: Option<bool>,
    warnings: &mut Vec<String>,
    errors: &mut Vec<String>,
) -> CargoResult<Vec<Target>> {
    let inferred = infer_from_directory(&package_root.join("tests"));

    let targets = clean_targets(
        "test",
        "test",
        toml_tests,
        &inferred,
        package_root,
        edition,
        autodiscover,
        warnings,
        errors,
        "autotests",
    )?;

    let mut result = Vec::new();
    for (path, toml) in targets {
        let mut target =
            Target::test_target(&toml.name(), path, toml.required_features.clone(), edition);
        configure(features, &toml, &mut target)?;
        result.push(target);
    }
    Ok(result)
}

fn clean_benches(
    features: &Features,
    toml_benches: Option<&Vec<TomlBenchTarget>>,
    package_root: &Path,
    edition: Edition,
    autodiscover: Option<bool>,
    warnings: &mut Vec<String>,
    errors: &mut Vec<String>,
) -> CargoResult<Vec<Target>> {
    let mut legacy_warnings = vec![];

    let targets = {
        let mut legacy_bench_path = |bench: &TomlTarget| {
            let legacy_path = package_root.join("src").join("bench.rs");
            if !(bench.name() == "bench" && legacy_path.exists()) {
                return None;
            }
            legacy_warnings.push(format!(
                "path `{}` was erroneously implicitly accepted for benchmark `{}`,\n\
                 please set bench.path in Cargo.toml",
                legacy_path.display(),
                bench.name()
            ));
            Some(legacy_path)
        };

        let inferred = infer_from_directory(&package_root.join("benches"));

        clean_targets_with_legacy_path(
            "benchmark",
            "bench",
            toml_benches,
            &inferred,
            package_root,
            edition,
            autodiscover,
            warnings,
            errors,
            &mut legacy_bench_path,
            "autobenches",
        )?
    };

    warnings.append(&mut legacy_warnings);

    let mut result = Vec::new();
    for (path, toml) in targets {
        let mut target =
            Target::bench_target(&toml.name(), path, toml.required_features.clone(), edition);
        configure(features, &toml, &mut target)?;
        result.push(target);
    }

    Ok(result)
}

fn clean_targets(
    target_kind_human: &str,
    target_kind: &str,
    toml_targets: Option<&Vec<TomlTarget>>,
    inferred: &[(String, PathBuf)],
    package_root: &Path,
    edition: Edition,
    autodiscover: Option<bool>,
    warnings: &mut Vec<String>,
    errors: &mut Vec<String>,
    autodiscover_flag_name: &str,
) -> CargoResult<Vec<(PathBuf, TomlTarget)>> {
    clean_targets_with_legacy_path(
        target_kind_human,
        target_kind,
        toml_targets,
        inferred,
        package_root,
        edition,
        autodiscover,
        warnings,
        errors,
        &mut |_| None,
        autodiscover_flag_name,
    )
}

fn clean_targets_with_legacy_path(
    target_kind_human: &str,
    target_kind: &str,
    toml_targets: Option<&Vec<TomlTarget>>,
    inferred: &[(String, PathBuf)],
    package_root: &Path,
    edition: Edition,
    autodiscover: Option<bool>,
    warnings: &mut Vec<String>,
    errors: &mut Vec<String>,
    legacy_path: &mut dyn FnMut(&TomlTarget) -> Option<PathBuf>,
    autodiscover_flag_name: &str,
) -> CargoResult<Vec<(PathBuf, TomlTarget)>> {
    let toml_targets = toml_targets_and_inferred(
        toml_targets,
        inferred,
        package_root,
        autodiscover,
        edition,
        warnings,
        target_kind_human,
        target_kind,
        autodiscover_flag_name,
    );

    for target in &toml_targets {
        validate_has_name(target, target_kind_human, target_kind)?;
    }

    validate_unique_names(&toml_targets, target_kind)?;
    let mut result = Vec::new();
    for target in toml_targets {
        let path = target_path(
            &target,
            inferred,
            target_kind,
            package_root,
            edition,
            legacy_path,
        );
        let path = match path {
            Ok(path) => path,
            Err(e) => {
                errors.push(e);
                continue;
            }
        };
        result.push((path, target));
    }
    Ok(result)
}

fn inferred_lib(package_root: &Path) -> Option<PathBuf> {
    let lib = package_root.join("src").join("lib.rs");
    if fs::metadata(&lib).is_ok() {
        Some(lib)
    } else {
        None
    }
}

fn inferred_bins(package_root: &Path, package_name: &str) -> Vec<(String, PathBuf)> {
    let main = package_root.join("src").join("main.rs");
    let mut result = Vec::new();
    if main.exists() {
        result.push((package_name.to_string(), main));
    }
    result.extend(infer_from_directory(&package_root.join("src").join("bin")));

    result
}

fn infer_from_directory(directory: &Path) -> Vec<(String, PathBuf)> {
    let entries = match fs::read_dir(directory) {
        Err(_) => return Vec::new(),
        Ok(dir) => dir,
    };

    entries
        .filter_map(|e| e.ok())
        .filter(is_not_dotfile)
        .filter_map(|d| infer_any(&d))
        .collect()
}

fn infer_any(entry: &DirEntry) -> Option<(String, PathBuf)> {
    if entry.path().extension().and_then(|p| p.to_str()) == Some("rs") {
        infer_file(entry)
    } else if entry.file_type().map(|t| t.is_dir()).ok() == Some(true) {
        infer_subdirectory(entry)
    } else {
        None
    }
}

fn infer_file(entry: &DirEntry) -> Option<(String, PathBuf)> {
    let path = entry.path();
    path.file_stem()
        .and_then(|p| p.to_str())
        .map(|p| (p.to_owned(), path.clone()))
}

fn infer_subdirectory(entry: &DirEntry) -> Option<(String, PathBuf)> {
    let path = entry.path();
    let main = path.join("main.rs");
    let name = path.file_name().and_then(|n| n.to_str());
    match (name, main.exists()) {
        (Some(name), true) => Some((name.to_owned(), main)),
        _ => None,
    }
}

fn is_not_dotfile(entry: &DirEntry) -> bool {
    entry.file_name().to_str().map(|s| s.starts_with('.')) == Some(false)
}

fn toml_targets_and_inferred(
    toml_targets: Option<&Vec<TomlTarget>>,
    inferred: &[(String, PathBuf)],
    package_root: &Path,
    autodiscover: Option<bool>,
    edition: Edition,
    warnings: &mut Vec<String>,
    target_kind_human: &str,
    target_kind: &str,
    autodiscover_flag_name: &str,
) -> Vec<TomlTarget> {
    let inferred_targets = inferred_to_toml_targets(inferred);
    match toml_targets {
        None => {
            if let Some(false) = autodiscover {
                vec![]
            } else {
                inferred_targets
            }
        }
        Some(targets) => {
            let mut targets = targets.clone();

            let target_path =
                |target: &TomlTarget| target.path.clone().map(|p| package_root.join(p.0));

            let mut seen_names = HashSet::new();
            let mut seen_paths = HashSet::new();
            for target in targets.iter() {
                seen_names.insert(target.name.clone());
                seen_paths.insert(target_path(target));
            }

            let mut rem_targets = vec![];
            for target in inferred_targets {
                if !seen_names.contains(&target.name) && !seen_paths.contains(&target_path(&target))
                {
                    rem_targets.push(target);
                }
            }

            let autodiscover = match autodiscover {
                Some(autodiscover) => autodiscover,
                None => {
                    if edition == Edition::Edition2015 {
                        if !rem_targets.is_empty() {
                            let mut rem_targets_str = String::new();
                            for t in rem_targets.iter() {
                                if let Some(p) = t.path.clone() {
                                    rem_targets_str.push_str(&format!("* {}\n", p.0.display()))
                                }
                            }
                            warnings.push(format!(
                                "\
An explicit [[{section}]] section is specified in Cargo.toml which currently
disables Cargo from automatically inferring other {target_kind_human} targets.
This inference behavior will change in the Rust 2018 edition and the following
files will be included as a {target_kind_human} target:

{rem_targets_str}
This is likely to break cargo build or cargo test as these files may not be
ready to be compiled as a {target_kind_human} target today. You can future-proof yourself
and disable this warning by adding `{autodiscover_flag_name} = false` to your [package]
section. You may also move the files to a location where Cargo would not
automatically infer them to be a target, such as in subfolders.

For more information on this warning you can consult
https://github.com/rust-lang/cargo/issues/5330",
                                section = target_kind,
                                target_kind_human = target_kind_human,
                                rem_targets_str = rem_targets_str,
                                autodiscover_flag_name = autodiscover_flag_name,
                            ));
                        };
                        false
                    } else {
                        true
                    }
                }
            };

            if autodiscover {
                targets.append(&mut rem_targets);
            }

            targets
        }
    }
}

fn inferred_to_toml_targets(inferred: &[(String, PathBuf)]) -> Vec<TomlTarget> {
    inferred
        .iter()
        .map(|&(ref name, ref path)| TomlTarget {
            name: Some(name.clone()),
            path: Some(PathValue(path.clone())),
            ..TomlTarget::new()
        })
        .collect()
}

fn validate_has_name(
    target: &TomlTarget,
    target_kind_human: &str,
    target_kind: &str,
) -> CargoResult<()> {
    match target.name {
        Some(ref name) => {
            if name.trim().is_empty() {
                failure::bail!("{} target names cannot be empty", target_kind_human)
            }
        }
        None => failure::bail!(
            "{} target {}.name is required",
            target_kind_human,
            target_kind
        ),
    }

    Ok(())
}

/// Will check a list of toml targets, and make sure the target names are unique within a vector.
fn validate_unique_names(targets: &[TomlTarget], target_kind: &str) -> CargoResult<()> {
    let mut seen = HashSet::new();
    for name in targets.iter().map(|e| e.name()) {
        if !seen.insert(name.clone()) {
            failure::bail!(
                "found duplicate {target_kind} name {name}, \
                 but all {target_kind} targets must have a unique name",
                target_kind = target_kind,
                name = name
            );
        }
    }
    Ok(())
}

fn configure(features: &Features, toml: &TomlTarget, target: &mut Target) -> CargoResult<()> {
    let t2 = target.clone();
    target
        .set_tested(toml.test.unwrap_or_else(|| t2.tested()))
        .set_doc(toml.doc.unwrap_or_else(|| t2.documented()))
        .set_doctest(toml.doctest.unwrap_or_else(|| t2.doctested()))
        .set_benched(toml.bench.unwrap_or_else(|| t2.benched()))
        .set_harness(toml.harness.unwrap_or_else(|| t2.harness()))
        .set_proc_macro(toml.proc_macro.unwrap_or_else(|| t2.proc_macro()))
        .set_for_host(match (toml.plugin, toml.proc_macro()) {
            (None, None) => t2.for_host(),
            (Some(true), _) | (_, Some(true)) => true,
            (Some(false), _) | (_, Some(false)) => false,
        });
    if let Some(edition) = toml.edition.clone() {
        features
            .require(Feature::edition())
            .chain_err(|| "editions are unstable")?;
        target.set_edition(
            edition
                .parse()
                .chain_err(|| "failed to parse the `edition` key")?,
        );
    }
    Ok(())
}

fn target_path(
    target: &TomlTarget,
    inferred: &[(String, PathBuf)],
    target_kind: &str,
    package_root: &Path,
    edition: Edition,
    legacy_path: &mut dyn FnMut(&TomlTarget) -> Option<PathBuf>,
) -> Result<PathBuf, String> {
    if let Some(ref path) = target.path {
        // Should we verify that this path exists here?
        return Ok(package_root.join(&path.0));
    }
    let name = target.name();

    let mut matching = inferred
        .iter()
        .filter(|&&(ref n, _)| n == &name)
        .map(|&(_, ref p)| p.clone());

    let first = matching.next();
    let second = matching.next();
    match (first, second) {
        (Some(path), None) => Ok(path),
        (None, None) | (Some(_), Some(_)) => {
            if edition == Edition::Edition2015 {
                if let Some(path) = legacy_path(target) {
                    return Ok(path);
                }
            }
            Err(format!(
                "can't find `{name}` {target_kind}, specify {target_kind}.path",
                name = name,
                target_kind = target_kind
            ))
        }
        (None, Some(_)) => unreachable!(),
    }
}