Skip to main content

cargo/ops/
cargo_compile.rs

1//!
2//! Cargo compile currently does the following steps:
3//!
4//! All configurations are already injected as environment variables via the
5//! main cargo command
6//!
7//! 1. Read the manifest
8//! 2. Shell out to `cargo-resolve` with a list of dependencies and sources as
9//!    stdin
10//!
11//!    a. Shell out to `--do update` and `--do list` for each source
12//!    b. Resolve dependencies and return a list of name/version/source
13//!
14//! 3. Shell out to `--do download` for each source
15//! 4. Shell out to `--do get` for each source, and build up the list of paths
16//!    to pass to rustc -L
17//! 5. Call `cargo-rustc` with the results of the resolver zipped together with
18//!    the results of the `get`
19//!
20//!    a. Topologically sort the dependencies
21//!    b. Compile each dependency in order, passing in the -L's pointing at each
22//!       previously compiled dependency
23//!
24
25use std::collections::{HashMap, HashSet};
26use std::path::PathBuf;
27use std::sync::Arc;
28
29use crate::core::compiler::{
30    BuildConfig, BuildContext, Compilation, Context, DefaultExecutor, Executor,
31};
32use crate::core::compiler::{CompileMode, Kind, Unit};
33use crate::core::profiles::{Profiles, UnitFor};
34use crate::core::resolver::{Method, Resolve};
35use crate::core::{Package, Source, Target};
36use crate::core::{PackageId, PackageIdSpec, TargetKind, Workspace};
37use crate::ops;
38use crate::util::config::Config;
39use crate::util::{lev_distance, profile, CargoResult};
40
41/// Contains information about how a package should be compiled.
42#[derive(Debug)]
43pub struct CompileOptions<'a> {
44    pub config: &'a Config,
45    /// Configuration information for a rustc build
46    pub build_config: BuildConfig,
47    /// Extra features to build for the root package
48    pub features: Vec<String>,
49    /// Flag whether all available features should be built for the root package
50    pub all_features: bool,
51    /// Flag if the default feature should be built for the root package
52    pub no_default_features: bool,
53    /// A set of packages to build.
54    pub spec: Packages,
55    /// Filter to apply to the root package to select which targets will be
56    /// built.
57    pub filter: CompileFilter,
58    /// Extra arguments to be passed to rustdoc (single target only)
59    pub target_rustdoc_args: Option<Vec<String>>,
60    /// The specified target will be compiled with all the available arguments,
61    /// note that this only accounts for the *final* invocation of rustc
62    pub target_rustc_args: Option<Vec<String>>,
63    /// Extra arguments passed to all selected targets for rustdoc.
64    pub local_rustdoc_args: Option<Vec<String>>,
65    /// The directory to copy final artifacts to. Note that even if `out_dir` is
66    /// set, a copy of artifacts still could be found a `target/(debug\release)`
67    /// as usual.
68    // Note that, although the cmd-line flag name is `out-dir`, in code we use
69    // `export_dir`, to avoid confusion with out dir at `target/debug/deps`.
70    pub export_dir: Option<PathBuf>,
71}
72
73impl<'a> CompileOptions<'a> {
74    pub fn new(config: &'a Config, mode: CompileMode) -> CargoResult<CompileOptions<'a>> {
75        Ok(CompileOptions {
76            config,
77            build_config: BuildConfig::new(config, None, &None, mode)?,
78            features: Vec::new(),
79            all_features: false,
80            no_default_features: false,
81            spec: ops::Packages::Packages(Vec::new()),
82            filter: CompileFilter::Default {
83                required_features_filterable: false,
84            },
85            target_rustdoc_args: None,
86            target_rustc_args: None,
87            local_rustdoc_args: None,
88            export_dir: None,
89        })
90    }
91}
92
93#[derive(Clone, PartialEq, Eq, Debug)]
94pub enum Packages {
95    Default,
96    All,
97    OptOut(Vec<String>),
98    Packages(Vec<String>),
99}
100
101impl Packages {
102    pub fn from_flags(all: bool, exclude: Vec<String>, package: Vec<String>) -> CargoResult<Self> {
103        Ok(match (all, exclude.len(), package.len()) {
104            (false, 0, 0) => Packages::Default,
105            (false, 0, _) => Packages::Packages(package),
106            (false, _, _) => failure::bail!("--exclude can only be used together with --all"),
107            (true, 0, _) => Packages::All,
108            (true, _, _) => Packages::OptOut(exclude),
109        })
110    }
111
112    pub fn to_package_id_specs(&self, ws: &Workspace<'_>) -> CargoResult<Vec<PackageIdSpec>> {
113        let specs = match *self {
114            Packages::All => ws
115                .members()
116                .map(Package::package_id)
117                .map(PackageIdSpec::from_package_id)
118                .collect(),
119            Packages::OptOut(ref opt_out) => ws
120                .members()
121                .map(Package::package_id)
122                .map(PackageIdSpec::from_package_id)
123                .filter(|p| opt_out.iter().position(|x| *x == p.name()).is_none())
124                .collect(),
125            Packages::Packages(ref packages) if packages.is_empty() => {
126                vec![PackageIdSpec::from_package_id(ws.current()?.package_id())]
127            }
128            Packages::Packages(ref packages) => packages
129                .iter()
130                .map(|p| PackageIdSpec::parse(p))
131                .collect::<CargoResult<Vec<_>>>()?,
132            Packages::Default => ws
133                .default_members()
134                .map(Package::package_id)
135                .map(PackageIdSpec::from_package_id)
136                .collect(),
137        };
138        if specs.is_empty() {
139            if ws.is_virtual() {
140                failure::bail!(
141                    "manifest path `{}` contains no package: The manifest is virtual, \
142                     and the workspace has no members.",
143                    ws.root().display()
144                )
145            }
146            failure::bail!("no packages to compile")
147        }
148        Ok(specs)
149    }
150
151    pub fn get_packages<'ws>(&self, ws: &'ws Workspace<'_>) -> CargoResult<Vec<&'ws Package>> {
152        let packages: Vec<_> = match self {
153            Packages::Default => ws.default_members().collect(),
154            Packages::All => ws.members().collect(),
155            Packages::OptOut(ref opt_out) => ws
156                .members()
157                .filter(|pkg| !opt_out.iter().any(|name| pkg.name().as_str() == name))
158                .collect(),
159            Packages::Packages(ref pkgs) => pkgs
160                .iter()
161                .map(|name| {
162                    ws.members()
163                        .find(|pkg| pkg.name().as_str() == name)
164                        .ok_or_else(|| {
165                            failure::format_err!(
166                                "package `{}` is not a member of the workspace",
167                                name
168                            )
169                        })
170                })
171                .collect::<CargoResult<Vec<_>>>()?,
172        };
173        Ok(packages)
174    }
175}
176
177#[derive(Debug)]
178pub enum FilterRule {
179    All,
180    Just(Vec<String>),
181}
182
183#[derive(Debug)]
184pub enum CompileFilter {
185    Default {
186        /// Flag whether targets can be safely skipped when required-features are not satisfied.
187        required_features_filterable: bool,
188    },
189    Only {
190        all_targets: bool,
191        lib: bool,
192        bins: FilterRule,
193        examples: FilterRule,
194        tests: FilterRule,
195        benches: FilterRule,
196    },
197}
198
199pub fn compile<'a>(
200    ws: &Workspace<'a>,
201    options: &CompileOptions<'a>,
202) -> CargoResult<Compilation<'a>> {
203    let exec: Arc<dyn Executor> = Arc::new(DefaultExecutor);
204    compile_with_exec(ws, options, &exec)
205}
206
207/// Like `compile` but allows specifying a custom `Executor` that will be able to intercept build
208/// calls and add custom logic. `compile` uses `DefaultExecutor` which just passes calls through.
209pub fn compile_with_exec<'a>(
210    ws: &Workspace<'a>,
211    options: &CompileOptions<'a>,
212    exec: &Arc<dyn Executor>,
213) -> CargoResult<Compilation<'a>> {
214    ws.emit_warnings()?;
215    compile_ws(ws, None, options, exec)
216}
217
218pub fn compile_ws<'a>(
219    ws: &Workspace<'a>,
220    source: Option<Box<dyn Source + 'a>>,
221    options: &CompileOptions<'a>,
222    exec: &Arc<dyn Executor>,
223) -> CargoResult<Compilation<'a>> {
224    let CompileOptions {
225        config,
226        ref build_config,
227        ref spec,
228        ref features,
229        all_features,
230        no_default_features,
231        ref filter,
232        ref target_rustdoc_args,
233        ref target_rustc_args,
234        ref local_rustdoc_args,
235        ref export_dir,
236    } = *options;
237
238    let default_arch_kind = if build_config.requested_target.is_some() {
239        Kind::Target
240    } else {
241        Kind::Host
242    };
243
244    let specs = spec.to_package_id_specs(ws)?;
245    let features = Method::split_features(features);
246    let method = Method::Required {
247        dev_deps: ws.require_optional_deps() || filter.need_dev_deps(build_config.mode),
248        features: &features,
249        all_features,
250        uses_default_features: !no_default_features,
251    };
252    let resolve = ops::resolve_ws_with_method(ws, source, method, &specs)?;
253    let (packages, resolve_with_overrides) = resolve;
254
255    let to_build_ids = specs
256        .iter()
257        .map(|s| s.query(resolve_with_overrides.iter()))
258        .collect::<CargoResult<Vec<_>>>()?;
259    let mut to_builds = packages.get_many(to_build_ids)?;
260
261    // The ordering here affects some error messages coming out of cargo, so
262    // let's be test and CLI friendly by always printing in the same order if
263    // there's an error.
264    to_builds.sort_by_key(|p| p.package_id());
265
266    for pkg in to_builds.iter() {
267        pkg.manifest().print_teapot(ws.config());
268
269        if build_config.mode.is_any_test()
270            && !ws.is_member(pkg)
271            && pkg.dependencies().iter().any(|dep| !dep.is_transitive())
272        {
273            failure::bail!(
274                "package `{}` cannot be tested because it requires dev-dependencies \
275                 and is not a member of the workspace",
276                pkg.name()
277            );
278        }
279    }
280
281    let (extra_args, extra_args_name) = match (target_rustc_args, target_rustdoc_args) {
282        (&Some(ref args), _) => (Some(args.clone()), "rustc"),
283        (_, &Some(ref args)) => (Some(args.clone()), "rustdoc"),
284        _ => (None, ""),
285    };
286
287    if extra_args.is_some() && to_builds.len() != 1 {
288        panic!(
289            "`{}` should not accept multiple `-p` flags",
290            extra_args_name
291        );
292    }
293
294    let profiles = ws.profiles();
295    profiles.validate_packages(&mut config.shell(), &packages)?;
296
297    let units = generate_targets(
298        ws,
299        profiles,
300        &to_builds,
301        filter,
302        default_arch_kind,
303        &resolve_with_overrides,
304        build_config,
305    )?;
306
307    let mut extra_compiler_args = HashMap::new();
308    if let Some(args) = extra_args {
309        if units.len() != 1 {
310            failure::bail!(
311                "extra arguments to `{}` can only be passed to one \
312                 target, consider filtering\nthe package by passing \
313                 e.g. `--lib` or `--bin NAME` to specify a single target",
314                extra_args_name
315            );
316        }
317        extra_compiler_args.insert(units[0], args);
318    }
319    if let Some(args) = local_rustdoc_args {
320        for unit in &units {
321            if unit.mode.is_doc() {
322                extra_compiler_args.insert(*unit, args.clone());
323            }
324        }
325    }
326
327    let ret = {
328        let _p = profile::start("compiling");
329        let bcx = BuildContext::new(
330            ws,
331            &resolve_with_overrides,
332            &packages,
333            config,
334            &build_config,
335            profiles,
336            extra_compiler_args,
337        )?;
338        let cx = Context::new(config, &bcx)?;
339        cx.compile(&units, export_dir.clone(), &exec)?
340    };
341
342    Ok(ret)
343}
344
345impl FilterRule {
346    pub fn new(targets: Vec<String>, all: bool) -> FilterRule {
347        if all {
348            FilterRule::All
349        } else {
350            FilterRule::Just(targets)
351        }
352    }
353
354    fn matches(&self, target: &Target) -> bool {
355        match *self {
356            FilterRule::All => true,
357            FilterRule::Just(ref targets) => targets.iter().any(|x| *x == target.name()),
358        }
359    }
360
361    fn is_specific(&self) -> bool {
362        match *self {
363            FilterRule::All => true,
364            FilterRule::Just(ref targets) => !targets.is_empty(),
365        }
366    }
367
368    pub fn try_collect(&self) -> Option<Vec<String>> {
369        match *self {
370            FilterRule::All => None,
371            FilterRule::Just(ref targets) => Some(targets.clone()),
372        }
373    }
374}
375
376impl CompileFilter {
377    pub fn new(
378        lib_only: bool,
379        bins: Vec<String>,
380        all_bins: bool,
381        tsts: Vec<String>,
382        all_tsts: bool,
383        exms: Vec<String>,
384        all_exms: bool,
385        bens: Vec<String>,
386        all_bens: bool,
387        all_targets: bool,
388    ) -> CompileFilter {
389        let rule_bins = FilterRule::new(bins, all_bins);
390        let rule_tsts = FilterRule::new(tsts, all_tsts);
391        let rule_exms = FilterRule::new(exms, all_exms);
392        let rule_bens = FilterRule::new(bens, all_bens);
393
394        if all_targets {
395            CompileFilter::Only {
396                all_targets: true,
397                lib: true,
398                bins: FilterRule::All,
399                examples: FilterRule::All,
400                benches: FilterRule::All,
401                tests: FilterRule::All,
402            }
403        } else if lib_only
404            || rule_bins.is_specific()
405            || rule_tsts.is_specific()
406            || rule_exms.is_specific()
407            || rule_bens.is_specific()
408        {
409            CompileFilter::Only {
410                all_targets: false,
411                lib: lib_only,
412                bins: rule_bins,
413                examples: rule_exms,
414                benches: rule_bens,
415                tests: rule_tsts,
416            }
417        } else {
418            CompileFilter::Default {
419                required_features_filterable: true,
420            }
421        }
422    }
423
424    pub fn need_dev_deps(&self, mode: CompileMode) -> bool {
425        match mode {
426            CompileMode::Test | CompileMode::Doctest | CompileMode::Bench => true,
427            CompileMode::Build | CompileMode::Doc { .. } | CompileMode::Check { .. } => match *self
428            {
429                CompileFilter::Default { .. } => false,
430                CompileFilter::Only {
431                    ref examples,
432                    ref tests,
433                    ref benches,
434                    ..
435                } => examples.is_specific() || tests.is_specific() || benches.is_specific(),
436            },
437            CompileMode::RunCustomBuild => panic!("Invalid mode"),
438        }
439    }
440
441    // this selects targets for "cargo run". for logic to select targets for
442    // other subcommands, see generate_targets and filter_default_targets
443    pub fn target_run(&self, target: &Target) -> bool {
444        match *self {
445            CompileFilter::Default { .. } => true,
446            CompileFilter::Only {
447                lib,
448                ref bins,
449                ref examples,
450                ref tests,
451                ref benches,
452                ..
453            } => {
454                let rule = match *target.kind() {
455                    TargetKind::Bin => bins,
456                    TargetKind::Test => tests,
457                    TargetKind::Bench => benches,
458                    TargetKind::ExampleBin | TargetKind::ExampleLib(..) => examples,
459                    TargetKind::Lib(..) => return lib,
460                    TargetKind::CustomBuild => return false,
461                };
462                rule.matches(target)
463            }
464        }
465    }
466
467    pub fn is_specific(&self) -> bool {
468        match *self {
469            CompileFilter::Default { .. } => false,
470            CompileFilter::Only { .. } => true,
471        }
472    }
473}
474
475/// A proposed target.
476///
477/// Proposed targets are later filtered into actual Units based on whether or
478/// not the target requires its features to be present.
479#[derive(Debug)]
480struct Proposal<'a> {
481    pkg: &'a Package,
482    target: &'a Target,
483    /// Indicates whether or not all required features *must* be present. If
484    /// false, and the features are not available, then it will be silently
485    /// skipped. Generally, targets specified by name (`--bin foo`) are
486    /// required, all others can be silently skipped if features are missing.
487    requires_features: bool,
488    mode: CompileMode,
489}
490
491/// Generates all the base targets for the packages the user has requested to
492/// compile. Dependencies for these targets are computed later in
493/// `unit_dependencies`.
494fn generate_targets<'a>(
495    ws: &Workspace<'_>,
496    profiles: &Profiles,
497    packages: &[&'a Package],
498    filter: &CompileFilter,
499    default_arch_kind: Kind,
500    resolve: &Resolve,
501    build_config: &BuildConfig,
502) -> CargoResult<Vec<Unit<'a>>> {
503    // Helper for creating a Unit struct.
504    let new_unit = |pkg: &'a Package, target: &'a Target, target_mode: CompileMode| {
505        let unit_for = if build_config.mode.is_any_test() {
506            // NOTE: The UnitFor here is subtle.  If you have a profile
507            // with `panic` set, the `panic` flag is cleared for
508            // tests/benchmarks and their dependencies.  If this
509            // was `normal`, then the lib would get compiled three
510            // times (once with panic, once without, and once with
511            // --test).
512            //
513            // This would cause a problem for Doc tests, which would fail
514            // because `rustdoc` would attempt to link with both libraries
515            // at the same time. Also, it's probably not important (or
516            // even desirable?) for rustdoc to link with a lib with
517            // `panic` set.
518            //
519            // As a consequence, Examples and Binaries get compiled
520            // without `panic` set.  This probably isn't a bad deal.
521            //
522            // Forcing the lib to be compiled three times during `cargo
523            // test` is probably also not desirable.
524            UnitFor::new_test()
525        } else if target.for_host() {
526            // proc-macro/plugin should not have `panic` set.
527            UnitFor::new_compiler()
528        } else {
529            UnitFor::new_normal()
530        };
531        // Custom build units are added in `build_unit_dependencies`.
532        assert!(!target.is_custom_build());
533        let target_mode = match target_mode {
534            CompileMode::Test => {
535                if target.is_example() && !filter.is_specific() && !target.tested() {
536                    // Examples are included as regular binaries to verify
537                    // that they compile.
538                    CompileMode::Build
539                } else {
540                    CompileMode::Test
541                }
542            }
543            CompileMode::Build => match *target.kind() {
544                TargetKind::Test => CompileMode::Test,
545                TargetKind::Bench => CompileMode::Bench,
546                _ => CompileMode::Build,
547            },
548            // CompileMode::Bench is only used to inform filter_default_targets
549            // which command is being used (`cargo bench`). Afterwards, tests
550            // and benches are treated identically. Switching the mode allows
551            // de-duplication of units that are essentially identical.  For
552            // example, `cargo build --all-targets --release` creates the units
553            // (lib profile:bench, mode:test) and (lib profile:bench, mode:bench)
554            // and since these are the same, we want them to be de-duped in
555            // `unit_dependencies`.
556            CompileMode::Bench => CompileMode::Test,
557            _ => target_mode,
558        };
559        // Plugins or proc-macro should be built for the host.
560        let kind = if target.for_host() {
561            Kind::Host
562        } else {
563            default_arch_kind
564        };
565        let profile = profiles.get_profile(
566            pkg.package_id(),
567            ws.is_member(pkg),
568            unit_for,
569            target_mode,
570            build_config.release,
571        );
572        Unit {
573            pkg,
574            target,
575            profile,
576            kind,
577            mode: target_mode,
578        }
579    };
580
581    // Create a list of proposed targets.
582    let mut proposals: Vec<Proposal<'_>> = Vec::new();
583
584    match *filter {
585        CompileFilter::Default {
586            required_features_filterable,
587        } => {
588            for pkg in packages {
589                let default = filter_default_targets(pkg.targets(), build_config.mode);
590                proposals.extend(default.into_iter().map(|target| Proposal {
591                    pkg,
592                    target,
593                    requires_features: !required_features_filterable,
594                    mode: build_config.mode,
595                }));
596                if build_config.mode == CompileMode::Test {
597                    if let Some(t) = pkg
598                        .targets()
599                        .iter()
600                        .find(|t| t.is_lib() && t.doctested() && t.doctestable())
601                    {
602                        proposals.push(Proposal {
603                            pkg,
604                            target: t,
605                            requires_features: false,
606                            mode: CompileMode::Doctest,
607                        });
608                    }
609                }
610            }
611        }
612        CompileFilter::Only {
613            all_targets,
614            lib,
615            ref bins,
616            ref examples,
617            ref tests,
618            ref benches,
619        } => {
620            if lib {
621                let mut libs = Vec::new();
622                for pkg in packages {
623                    for target in pkg.targets().iter().filter(|t| t.is_lib()) {
624                        if build_config.mode == CompileMode::Doctest && !target.doctestable() {
625                            ws.config()
626                                .shell()
627                                .warn(format!(
628                                "doc tests are not supported for crate type(s) `{}` in package `{}`",
629                                target.rustc_crate_types().join(", "),
630                                pkg.name()
631                            ))?;
632                        } else {
633                            libs.push(Proposal {
634                                pkg,
635                                target,
636                                requires_features: false,
637                                mode: build_config.mode,
638                            });
639                        }
640                    }
641                }
642                if !all_targets && libs.is_empty() {
643                    let names = packages.iter().map(|pkg| pkg.name()).collect::<Vec<_>>();
644                    if names.len() == 1 {
645                        failure::bail!("no library targets found in package `{}`", names[0]);
646                    } else {
647                        failure::bail!(
648                            "no library targets found in packages: {}",
649                            names.join(", ")
650                        );
651                    }
652                }
653                proposals.extend(libs);
654            }
655
656            // If --tests was specified, add all targets that would be
657            // generated by `cargo test`.
658            let test_filter = match *tests {
659                FilterRule::All => Target::tested,
660                FilterRule::Just(_) => Target::is_test,
661            };
662            let test_mode = match build_config.mode {
663                CompileMode::Build => CompileMode::Test,
664                CompileMode::Check { .. } => CompileMode::Check { test: true },
665                _ => build_config.mode,
666            };
667            // If --benches was specified, add all targets that would be
668            // generated by `cargo bench`.
669            let bench_filter = match *benches {
670                FilterRule::All => Target::benched,
671                FilterRule::Just(_) => Target::is_bench,
672            };
673            let bench_mode = match build_config.mode {
674                CompileMode::Build => CompileMode::Bench,
675                CompileMode::Check { .. } => CompileMode::Check { test: true },
676                _ => build_config.mode,
677            };
678
679            proposals.extend(list_rule_targets(
680                packages,
681                bins,
682                "bin",
683                Target::is_bin,
684                build_config.mode,
685            )?);
686            proposals.extend(list_rule_targets(
687                packages,
688                examples,
689                "example",
690                Target::is_example,
691                build_config.mode,
692            )?);
693            proposals.extend(list_rule_targets(
694                packages,
695                tests,
696                "test",
697                test_filter,
698                test_mode,
699            )?);
700            proposals.extend(list_rule_targets(
701                packages,
702                benches,
703                "bench",
704                bench_filter,
705                bench_mode,
706            )?);
707        }
708    }
709
710    // Only include targets that are libraries or have all required
711    // features available.
712    let mut features_map = HashMap::new();
713    let mut units = HashSet::new();
714    for Proposal {
715        pkg,
716        target,
717        requires_features,
718        mode,
719    } in proposals
720    {
721        let unavailable_features = match target.required_features() {
722            Some(rf) => {
723                let features = features_map
724                    .entry(pkg)
725                    .or_insert_with(|| resolve_all_features(resolve, pkg.package_id()));
726                rf.iter().filter(|f| !features.contains(*f)).collect()
727            }
728            None => Vec::new(),
729        };
730        if target.is_lib() || unavailable_features.is_empty() {
731            let unit = new_unit(pkg, target, mode);
732            units.insert(unit);
733        } else if requires_features {
734            let required_features = target.required_features().unwrap();
735            let quoted_required_features: Vec<String> = required_features
736                .iter()
737                .map(|s| format!("`{}`", s))
738                .collect();
739            failure::bail!(
740                "target `{}` in package `{}` requires the features: {}\n\
741                 Consider enabling them by passing e.g. `--features=\"{}\"`",
742                target.name(),
743                pkg.name(),
744                quoted_required_features.join(", "),
745                required_features.join(" ")
746            );
747        }
748        // else, silently skip target.
749    }
750    Ok(units.into_iter().collect())
751}
752
753fn resolve_all_features(
754    resolve_with_overrides: &Resolve,
755    package_id: PackageId,
756) -> HashSet<String> {
757    let mut features = resolve_with_overrides.features(package_id).clone();
758
759    // Include features enabled for use by dependencies so targets can also use them with the
760    // required-features field when deciding whether to be built or skipped.
761    for (dep, _) in resolve_with_overrides.deps(package_id) {
762        for feature in resolve_with_overrides.features(dep) {
763            features.insert(dep.name().to_string() + "/" + feature);
764        }
765    }
766
767    features
768}
769
770/// Given a list of all targets for a package, filters out only the targets
771/// that are automatically included when the user doesn't specify any targets.
772fn filter_default_targets(targets: &[Target], mode: CompileMode) -> Vec<&Target> {
773    match mode {
774        CompileMode::Bench => targets.iter().filter(|t| t.benched()).collect(),
775        CompileMode::Test => targets
776            .iter()
777            .filter(|t| t.tested() || t.is_example())
778            .collect(),
779        CompileMode::Build | CompileMode::Check { .. } => targets
780            .iter()
781            .filter(|t| t.is_bin() || t.is_lib())
782            .collect(),
783        CompileMode::Doc { .. } => {
784            // `doc` does lib and bins (bin with same name as lib is skipped).
785            targets
786                .iter()
787                .filter(|t| {
788                    t.documented()
789                        && (!t.is_bin()
790                            || !targets.iter().any(|l| l.is_lib() && l.name() == t.name()))
791                })
792                .collect()
793        }
794        CompileMode::Doctest | CompileMode::RunCustomBuild => panic!("Invalid mode {:?}", mode),
795    }
796}
797
798/// Returns a list of targets based on command-line target selection flags.
799/// The return value is a list of `(Package, Target, bool, CompileMode)`
800/// tuples.  The `bool` value indicates whether or not all required features
801/// *must* be present.
802fn list_rule_targets<'a>(
803    packages: &[&'a Package],
804    rule: &FilterRule,
805    target_desc: &'static str,
806    is_expected_kind: fn(&Target) -> bool,
807    mode: CompileMode,
808) -> CargoResult<Vec<Proposal<'a>>> {
809    let mut result = Vec::new();
810    match *rule {
811        FilterRule::All => {
812            for pkg in packages {
813                for target in pkg.targets() {
814                    if is_expected_kind(target) {
815                        result.push(Proposal {
816                            pkg,
817                            target,
818                            requires_features: false,
819                            mode,
820                        });
821                    }
822                }
823            }
824        }
825        FilterRule::Just(ref names) => {
826            for name in names {
827                result.extend(find_named_targets(
828                    packages,
829                    name,
830                    target_desc,
831                    is_expected_kind,
832                    mode,
833                )?);
834            }
835        }
836    }
837    Ok(result)
838}
839
840/// Find the targets for a specifically named target.
841fn find_named_targets<'a>(
842    packages: &[&'a Package],
843    target_name: &str,
844    target_desc: &'static str,
845    is_expected_kind: fn(&Target) -> bool,
846    mode: CompileMode,
847) -> CargoResult<Vec<Proposal<'a>>> {
848    let mut result = Vec::new();
849    for pkg in packages {
850        for target in pkg.targets() {
851            if target.name() == target_name && is_expected_kind(target) {
852                result.push(Proposal {
853                    pkg,
854                    target,
855                    requires_features: true,
856                    mode,
857                });
858            }
859        }
860    }
861    if result.is_empty() {
862        let suggestion = packages
863            .iter()
864            .flat_map(|pkg| {
865                pkg.targets()
866                    .iter()
867                    .filter(|target| is_expected_kind(target))
868            })
869            .map(|target| (lev_distance(target_name, target.name()), target))
870            .filter(|&(d, _)| d < 4)
871            .min_by_key(|t| t.0)
872            .map(|t| t.1);
873        match suggestion {
874            Some(s) => failure::bail!(
875                "no {} target named `{}`\n\nDid you mean `{}`?",
876                target_desc,
877                target_name,
878                s.name()
879            ),
880            None => failure::bail!("no {} target named `{}`", target_desc, target_name),
881        }
882    }
883    Ok(result)
884}