1 //! lint on multiple versions of a crate being used
3 use clippy_utils::diagnostics::span_lint;
4 use clippy_utils::is_lint_allowed;
5 use rustc_hir::def_id::LOCAL_CRATE;
6 use rustc_hir::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! {
17 /// Checks to see if multiple versions of a crate are being
20 /// ### Why is this bad?
21 /// This bloats the size of targets, and can lead to
22 /// confusing error messages when structs or traits are used interchangeably
23 /// between different versions of a crate.
25 /// ### Known problems
26 /// Because this can be caused purely by the dependencies
27 /// themselves, it's not always possible to fix this issue.
31 /// # This will pull in both winapi v0.3.x and v0.2.x, triggering a warning.
34 /// ansi_term = "=0.11.0"
36 #[clippy::version = "pre 1.29.0"]
37 pub MULTIPLE_CRATE_VERSIONS,
39 "multiple versions of the same crate being used"
42 declare_lint_pass!(MultipleCrateVersions => [MULTIPLE_CRATE_VERSIONS]);
44 impl LateLintPass<'_> for MultipleCrateVersions {
45 fn check_crate(&mut self, cx: &LateContext<'_>) {
46 if is_lint_allowed(cx, MULTIPLE_CRATE_VERSIONS, CRATE_HIR_ID) {
50 let metadata = unwrap_cargo_metadata!(cx, MULTIPLE_CRATE_VERSIONS, true);
51 let local_name = cx.tcx.crate_name(LOCAL_CRATE).as_str();
52 let mut packages = metadata.packages;
53 packages.sort_by(|a, b| a.name.cmp(&b.name));
56 if let Some(resolve) = &metadata.resolve;
57 if let Some(local_id) = packages
59 .find_map(|p| if p.name == *local_name { Some(&p.id) } else { None });
61 for (name, group) in &packages.iter().group_by(|p| p.name.clone()) {
62 let group: Vec<&Package> = group.collect();
68 if group.iter().all(|p| is_normal_dep(&resolve.nodes, local_id, &p.id)) {
69 let mut versions: Vec<_> = group.into_iter().map(|p| &p.version).collect();
71 let versions = versions.iter().join(", ");
75 MULTIPLE_CRATE_VERSIONS,
77 &format!("multiple versions for dependency `{}`: {}", name, versions),
86 fn is_normal_dep(nodes: &[Node], local_id: &PackageId, dep_id: &PackageId) -> bool {
87 fn depends_on(node: &Node, dep_id: &PackageId) -> bool {
88 node.deps.iter().any(|dep| {
93 .any(|info| matches!(info.kind, DependencyKind::Normal))
99 .filter(|node| depends_on(node, dep_id))
100 .any(|node| node.id == *local_id || is_normal_dep(nodes, local_id, &node.id))