]> git.lizzy.rs Git - rust.git/blobdiff - clippy_lints/src/utils/mod.rs
Auto merge of #4551 - mikerite:fix-ice-reporting, r=llogiq
[rust.git] / clippy_lints / src / utils / mod.rs
index bcb443158397e2b36e7bc9b5f66c0a4e70541b33..9165f8d74d7831bc1f2e453a2b58100db5d1260f 100644 (file)
@@ -47,6 +47,7 @@
 use syntax::source_map::{Span, DUMMY_SP};
 use syntax::symbol::{kw, Symbol};
 
+use crate::consts::{constant, Constant};
 use crate::reexport::*;
 
 /// Returns `true` if the two spans come from differing expansions (i.e., one is
@@ -272,6 +273,19 @@ pub fn path_to_res(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<(def::Res)
     }
 }
 
+pub fn qpath_res(cx: &LateContext<'_, '_>, qpath: &hir::QPath, id: hir::HirId) -> Res {
+    match qpath {
+        hir::QPath::Resolved(_, path) => path.res,
+        hir::QPath::TypeRelative(..) => {
+            if cx.tcx.has_typeck_tables(id.owner_def_id()) {
+                cx.tcx.typeck_tables_of(id.owner_def_id()).qpath_res(qpath, id)
+            } else {
+                Res::Err
+            }
+        },
+    }
+}
+
 /// Convenience function to get the `DefId` of a trait by path.
 /// It could be a trait or trait alias.
 pub fn get_trait_def_id(cx: &LateContext<'_, '_>, path: &[&str]) -> Option<DefId> {
@@ -669,6 +683,24 @@ fn inner(ty: Ty<'_>, depth: usize) -> (Ty<'_>, usize) {
     inner(ty, 0)
 }
 
+/// Checks whether the given expression is a constant integer of the given value.
+/// unlike `is_integer_literal`, this version does const folding
+pub fn is_integer_const(cx: &LateContext<'_, '_>, e: &Expr, value: u128) -> bool {
+    if is_integer_literal(e, value) {
+        return true;
+    }
+    let map = cx.tcx.hir();
+    let parent_item = map.get_parent_item(e.hir_id);
+    if let Some((Constant::Int(v), _)) = map
+        .maybe_body_owned_by(parent_item)
+        .and_then(|body_id| constant(cx, cx.tcx.body_tables(body_id), e))
+    {
+        value == v
+    } else {
+        false
+    }
+}
+
 /// Checks whether the given expression is a constant literal of the given value.
 pub fn is_integer_literal(expr: &Expr, value: u128) -> bool {
     // FIXME: use constant folding