cargo 0.100.0

Cargo, a package manager for Rust.
Documentation
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
use std::collections::VecDeque;
use std::path::Path;

use crate::util::data_structures::{HashSet, IndexMap};
use cargo_util_schemas::manifest;
use cargo_util_schemas::manifest::TomlPackageBuild;
use cargo_util_terminal::report::AnnotationKind;
use cargo_util_terminal::report::Group;
use cargo_util_terminal::report::Level;
use cargo_util_terminal::report::Origin;
use cargo_util_terminal::report::Snippet;
use tracing::{debug, instrument, trace};

use super::STYLE;
use crate::CargoResult;
use crate::GlobalContext;
use crate::compiler::BuildContext;
use crate::compiler::BuildRunner;
use crate::compiler::Unit;
use crate::compiler::unused_deps::DependenciesState;
use crate::compiler::unused_deps::UnusedDepState;
use crate::diagnostics::GlobalDiagnosticStats;
use crate::diagnostics::Lint;
use crate::diagnostics::LintLevel;
use crate::diagnostics::LintLevelProduct;
use crate::diagnostics::ScopedDiagnosticStats;
use crate::diagnostics::get_key_value_span;
use crate::diagnostics::workspace_rel_path;
use crate::workspace::Package;
use crate::workspace::PackageId;
use crate::workspace::Workspace;
use crate::workspace::dependency::DepKind;

pub static LINT: &Lint = &Lint {
    name: "unused_dependencies",
    primary_group: &STYLE,
    msrv: Some(super::CARGO_LINTS_MSRV),
    feature_gate: None,
    docs: Some(
        r#"
### What it does

Checks for dependencies that are not used by any of the cargo targets.

### Why is this bad?

Slows down compilation time.

### Drawbacks

The lint is only emitted in specific circumstances as multiple cargo targets exist for the
different dependencies tables and they must all be built to know if a dependency is unused.
Currently, only the selected packages are checked and not all `path` dependencies like most lints.
The cargo target selection flags,
independent of which packages are selected, determine which dependencies tables are checked.
As there is no way to select all cargo targets that use `[dev-dependencies]`,
they are unchecked.

Examples:
- `cargo check` will lint `[build-dependencies]` and `[dependencies]`
- `cargo check --all-targets` will still only lint `[build-dependencies]` and `[dependencies]` and not `[dev-dependencoes]`
- `cargo check --bin foo` will not lint `[dependencies]` even if `foo` is the only bin though `[build-dependencies]` will be checked
- `cargo check -p foo` will not lint any dependencies tables for the `path` dependency `bar` even if `bar` only has a `[lib]`

There can be false positives when depending on a transitive dependency to activate a feature.

For false positives from pinning the version of a transitive dependency in `Cargo.toml`,
move the dependency to the `target."cfg(false)".dependencies` table.

### Example

```toml
[package]
name = "foo"

[dependencies]
unused = "1"
```

Should be written as:

```toml
[package]
name = "foo"
```
"#,
    ),
};

/// Lint for `[build-dependencies]` without a `build.rs`
///
/// These are always unused.
///
/// This must be determined independent of the compiler since there are no build targets to pass to
/// rustc to report on these.
#[instrument(skip_all)]
pub(crate) fn lint_package(
    ws: &Workspace<'_>,
    pkg: &Package,
    manifest_path: &Path,
    level: LintLevelProduct,
    pkg_stats: &mut ScopedDiagnosticStats<'_>,
    gctx: &GlobalContext,
) -> CargoResult<()> {
    let LintLevelProduct {
        level: lint_level,
        source,
    } = level;

    let manifest_path = workspace_rel_path(ws, manifest_path);

    let manifest = pkg.manifest();
    let Some(package) = &manifest.normalized_toml().package else {
        return Ok(());
    };
    if package.build != Some(TomlPackageBuild::Auto(false)) {
        return Ok(());
    }

    let document = manifest.document();
    let contents = manifest.contents();

    for (i, dep_name) in manifest
        .normalized_toml()
        .build_dependencies()
        .iter()
        .flat_map(|m| m.keys())
        .enumerate()
    {
        let level = lint_level.to_diagnostic_level();
        let emitted_source = LINT.emitted_source(lint_level, source);

        let mut primary =
            Group::with_title(level.primary_title(format!("unused build dependency `{dep_name}`")));
        if let Some(document) = document
            && let Some(contents) = contents
            && let Some(span) = get_key_value_span(document, &["build-dependencies", dep_name])
        {
            let span = span.key.start..span.value.end;
            primary = primary.element(
                Snippet::source(contents)
                    .path(&manifest_path)
                    .annotation(AnnotationKind::Primary.span(span)),
            );
        } else {
            primary = primary.element(Origin::path(&manifest_path));
        }
        if i == 0 {
            primary = primary.element(Level::NOTE.message(emitted_source));
        }
        let mut report = vec![primary];
        let help = Group::with_title(
            Level::HELP
                .secondary_title(format!("consider removing the dependency on `{dep_name}`")),
        );
        report.push(help);

        pkg_stats.record_lint(lint_level);
        gctx.shell().print_report(&report, lint_level.force())?;
    }

    Ok(())
}

#[instrument(skip_all)]
pub fn lint_build_results(
    build_runner: &BuildRunner<'_, '_>,
    global_stats: &mut GlobalDiagnosticStats,
) -> CargoResult<()> {
    for (pkg_id, states) in &build_runner.unused_dep_state.states {
        let Some(pkg) = get_package(&build_runner.unused_dep_state, pkg_id) else {
            continue;
        };
        let toml_lints = pkg
            .manifest()
            .normalized_toml()
            .lints
            .clone()
            .map(|lints| lints.lints)
            .unwrap_or(manifest::TomlLints::default());
        let cargo_lints = toml_lints
            .get("cargo")
            .cloned()
            .unwrap_or(manifest::TomlToolLints::default());
        let level = LINT.level(
            &cargo_lints,
            pkg.rust_version(),
            pkg.manifest().unstable_features(),
            build_runner.bcx.gctx,
        );
        if !pkg_id.source_id().is_path() {
            for (dep_kind, state) in states.iter() {
                for ext in state.unused_externs.iter().flatten() {
                    debug!(
                        "pkg {} v{} ({dep_kind:?}): ignoring unused extern `{ext}`, package is capped",
                        pkg_id.name(),
                        pkg_id.version(),
                    );
                }
            }
            continue;
        }
        if level.level == LintLevel::Allow {
            for (dep_kind, state) in states.iter() {
                for ext in state.unused_externs.iter().flatten() {
                    debug!(
                        "pkg {} v{} ({dep_kind:?}): ignoring unused extern `{ext}`, lint is allowed",
                        pkg_id.name(),
                        pkg_id.version(),
                    );
                }
            }
            continue;
        }

        let mut pkg_stats = global_stats.scope();
        lint_package_build_results(build_runner, pkg, states, level, &mut pkg_stats)?;
        pkg_stats.report_summary("finalize", Some(&*pkg.name()), build_runner.bcx.gctx)?;
    }
    Ok(())
}

fn lint_package_build_results(
    build_runner: &BuildRunner<'_, '_>,
    pkg: &Package,
    states: &IndexMap<DepKind, DependenciesState>,
    level: LintLevelProduct,
    pkg_stats: &mut ScopedDiagnosticStats<'_>,
) -> CargoResult<()> {
    let mut lint_count = 0;
    let LintLevelProduct {
        level: lint_level,
        source,
    } = level;
    let ws = build_runner.bcx.ws;
    let manifest_path = workspace_rel_path(ws, pkg.manifest_path());
    let pkg_id = pkg.package_id();
    for (dep_kind, state) in states.iter() {
        for ext in state.unused_externs.iter().flatten() {
            let mut used_in_dev = false;
            match dep_kind {
                DepKind::Normal => {
                    if let Some(state) = states.get(&DepKind::Development)
                        && state
                            .unused_externs
                            .as_ref()
                            .is_some_and(|ue| !ue.contains(ext))
                    {
                        used_in_dev = true;
                    }
                }
                DepKind::Development => {
                    if let Some(state) = states.get(&DepKind::Normal)
                        && state.externs.contains_key(ext)
                    {
                        trace!(
                            "pkg {} v{} ({dep_kind:?}): ignoring unused extern `{ext}`, inherited from normal dependency",
                            pkg_id.name(),
                            pkg_id.version(),
                        );
                        continue;
                    }
                }
                DepKind::Build => {}
            }
            let Some(extern_state) = state.externs.get(ext) else {
                // not one we care to report
                debug!(
                    "pkg {} v{} ({dep_kind:?}): ignoring unused extern `{ext}`, untracked dependent",
                    pkg_id.name(),
                    pkg_id.version(),
                );
                continue;
            };
            if state.seen_units.len() != state.needed_units {
                debug_assert_ne!(state.externs.len(), 0, "assumes tracked is checked first");
                // Some compilations errored without printing the unused externs.
                // Don't print the warning in order to reduce false positive
                // spam during errors.
                debug!(
                    "pkg {} v{} ({dep_kind:?}): ignoring unused extern `{ext}`, {} outstanding units",
                    pkg_id.name(),
                    pkg_id.version(),
                    state.needed_units - state.seen_units.len()
                );
                continue;
            }
            if is_transitive_dep(&extern_state.unit, &state.seen_units, build_runner.bcx) {
                debug!(
                    "pkg {} v{} ({dep_kind:?}): ignoring unused extern `{ext}`, may be activating features",
                    pkg_id.name(),
                    pkg_id.version(),
                );
                continue;
            }

            // Implicitly added dependencies (in the same crate) aren't interesting
            let dependency = if let Some(dependency) = &extern_state.manifest_deps {
                dependency
            } else {
                continue;
            };
            for dependency in dependency {
                let manifest = pkg.manifest();
                let document = manifest.document();
                let contents = manifest.contents();
                let level = lint_level.to_diagnostic_level();
                let emitted_source = LINT.emitted_source(lint_level, source);
                let toml_path = dependency.toml_path();
                let dep_name = toml_path.last().unwrap();

                let mut primary = Group::with_title(
                    level.primary_title(format!("unused dependency `{dep_name}`")),
                );
                if let Some(document) = document
                    && let Some(contents) = contents
                    && let Some(span) = get_key_value_span(document, &toml_path)
                {
                    let span = span.key.start..span.value.end;
                    primary = primary.element(
                        Snippet::source(contents)
                            .path(&manifest_path)
                            .annotation(AnnotationKind::Primary.span(span)),
                    );
                } else {
                    primary = primary.element(Origin::path(&manifest_path));
                }
                if lint_count == 0 {
                    primary = primary.element(Level::NOTE.message(emitted_source));
                }
                lint_count += 1;
                let mut report = vec![primary];
                let help =
                    Group::with_title(Level::HELP.secondary_title(format!(
                        "consider removing the dependency on `{dep_name}`"
                    )));
                report.push(help);
                if used_in_dev {
                    let help = Group::with_title(Level::HELP.secondary_title(
                        "to still use for development builds, move to `dev-dependencies`",
                    ));
                    report.push(help);
                }

                pkg_stats.record_lint(lint_level);
                build_runner
                    .bcx
                    .gctx
                    .shell()
                    .print_report(&report, lint_level.force())?;
            }
        }
    }
    Ok(())
}

fn get_package<'s>(
    unused_dep_state: &'s UnusedDepState,
    pkg_id: &PackageId,
) -> Option<&'s Package> {
    let state = unused_dep_state.states.get(pkg_id)?;
    let mut iter = state.values();
    let state = iter.next()?;
    let mut iter = state.seen_units.iter();
    let unit = iter.next()?;
    Some(&unit.pkg)
}

#[instrument(skip_all)]
fn is_transitive_dep(
    direct_dep_unit: &Unit,
    seen_units: &Vec<Unit>,
    bcx: &BuildContext<'_, '_>,
) -> bool {
    let mut queue = VecDeque::new();
    let mut visited: HashSet<&Unit> = HashSet::default();
    for root_unit in seen_units {
        for unit_dep in &bcx.unit_graph[root_unit] {
            if root_unit.pkg.package_id() == unit_dep.unit.pkg.package_id() {
                continue;
            }
            if unit_dep.unit == *direct_dep_unit {
                continue;
            }
            if visited.insert(&unit_dep.unit) {
                queue.push_back(&unit_dep.unit);
            }
        }
    }

    while let Some(dep_unit) = queue.pop_front() {
        for unit_dep in &bcx.unit_graph[dep_unit] {
            if unit_dep.unit == *direct_dep_unit {
                return true;
            }
            if visited.insert(&unit_dep.unit) {
                queue.push_back(&unit_dep.unit);
            }
        }
    }

    false
}