1 //! lint on multiple versions of a crate being used
3 use clippy_utils::diagnostics::span_lint;
4 use clippy_utils::run_lints;
5 use rustc_hir::def_id::LOCAL_CRATE;
6 use rustc_hir::{Crate, CRATE_HIR_ID};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::DUMMY_SP;
11 use cargo_metadata::{DependencyKind, Node, Package, PackageId};
12 use if_chain::if_chain;
13 use itertools::Itertools;
15 declare_clippy_lint! {
16 /// **What it does:** Checks to see if multiple versions of a crate are being
19 /// **Why is this bad?** This bloats the size of targets, and can lead to
20 /// confusing error messages when structs or traits are used interchangeably
21 /// between different versions of a crate.
23 /// **Known problems:** Because this can be caused purely by the dependencies
24 /// themselves, it's not always possible to fix this issue.
28 /// # This will pull in both winapi v0.3.x and v0.2.x, triggering a warning.
31 /// ansi_term = "=0.11.0"
33 pub MULTIPLE_CRATE_VERSIONS,
35 "multiple versions of the same crate being used"
38 declare_lint_pass!(MultipleCrateVersions => [MULTIPLE_CRATE_VERSIONS]);
40 impl LateLintPass<'_> for MultipleCrateVersions {
41 fn check_crate(&mut self, cx: &LateContext<'_>, _: &Crate<'_>) {
42 if !run_lints(cx, &[MULTIPLE_CRATE_VERSIONS], CRATE_HIR_ID) {
46 let metadata = unwrap_cargo_metadata!(cx, MULTIPLE_CRATE_VERSIONS, true);
47 let local_name = cx.tcx.crate_name(LOCAL_CRATE).as_str();
48 let mut packages = metadata.packages;
49 packages.sort_by(|a, b| a.name.cmp(&b.name));
52 if let Some(resolve) = &metadata.resolve;
53 if let Some(local_id) = packages
55 .find_map(|p| if p.name == *local_name { Some(&p.id) } else { None });
57 for (name, group) in &packages.iter().group_by(|p| p.name.clone()) {
58 let group: Vec<&Package> = group.collect();
64 if group.iter().all(|p| is_normal_dep(&resolve.nodes, local_id, &p.id)) {
65 let mut versions: Vec<_> = group.into_iter().map(|p| &p.version).collect();
67 let versions = versions.iter().join(", ");
71 MULTIPLE_CRATE_VERSIONS,
73 &format!("multiple versions for dependency `{}`: {}", name, versions),
82 fn is_normal_dep(nodes: &[Node], local_id: &PackageId, dep_id: &PackageId) -> bool {
83 fn depends_on(node: &Node, dep_id: &PackageId) -> bool {
84 node.deps.iter().any(|dep| {
89 .any(|info| matches!(info.kind, DependencyKind::Normal))
95 .filter(|node| depends_on(node, dep_id))
96 .any(|node| node.id == *local_id || is_normal_dep(nodes, local_id, &node.id))