-#![allow(clippy::default_hash_types)]
+#![allow(rustc::default_hash_types)]
+
+use std::borrow::Cow;
+use std::cmp::Ordering;
+use std::collections::BTreeMap;
-use crate::consts::{constant, Constant};
-use crate::utils::paths;
-use crate::utils::{
- clip, comparisons, differing_macro_contexts, higher, in_constant, in_macro, int_bits, last_path_segment,
- match_def_path, match_path, multispan_sugg, same_tys, sext, snippet, snippet_opt, snippet_with_applicability,
- span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then, unsext, AbsolutePathBuffer,
-};
use if_chain::if_chain;
use rustc::hir;
use rustc::hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
use rustc::hir::*;
use rustc::lint::{in_external_macro, LateContext, LateLintPass, LintArray, LintContext, LintPass};
use rustc::ty::layout::LayoutOf;
-use rustc::ty::{self, Ty, TyCtxt, TypeckTables};
-use rustc::{declare_tool_lint, lint_array};
+use rustc::ty::{self, InferTy, Ty, TyCtxt, TypeckTables};
+use rustc::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
use rustc_errors::Applicability;
use rustc_target::spec::abi::Abi;
use rustc_typeck::hir_ty_to_ty;
-use std::borrow::Cow;
-use std::cmp::Ordering;
-use std::collections::BTreeMap;
-use syntax::ast::{FloatTy, IntTy, UintTy};
+use syntax::ast::{FloatTy, IntTy, LitIntType, LitKind, UintTy};
use syntax::errors::DiagnosticBuilder;
use syntax::source_map::Span;
+use syntax::symbol::{sym, Symbol};
-/// Handles all the linting of funky types
-pub struct TypePass;
+use crate::consts::{constant, Constant};
+use crate::utils::paths;
+use crate::utils::{
+ clip, comparisons, differing_macro_contexts, higher, in_constant, int_bits, last_path_segment, match_def_path,
+ match_path, multispan_sugg, qpath_res, same_tys, sext, snippet, snippet_opt, snippet_with_applicability,
+ snippet_with_macro_callsite, span_help_and_lint, span_lint, span_lint_and_sugg, span_lint_and_then, unsext,
+};
declare_clippy_lint! {
/// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
/// **Known problems:** None.
///
/// **Example:**
- /// ```rust
+ /// ```rust,ignore
/// struct X {
/// values: Box<Vec<Foo>>,
/// }
///
/// Better:
///
- /// ```rust
+ /// ```rust,ignore
/// struct X {
/// values: Vec<Foo>,
/// }
/// fn x() -> Option<Option<u32>> {
/// None
/// }
+ /// ```
pub OPTION_OPTION,
complexity,
"usage of `Option<Option<T>>`"
///
/// **Example:**
/// ```rust
- /// let x = LinkedList::new();
+ /// # use std::collections::LinkedList;
+ /// let x: LinkedList<usize> = LinkedList::new();
/// ```
pub LINKEDLIST,
pedantic,
/// **Known problems:** None.
///
/// **Example:**
- /// ```rust
+ /// ```rust,ignore
/// fn foo(bar: &Box<T>) { ... }
/// ```
///
/// Better:
///
- /// ```rust
+ /// ```rust,ignore
/// fn foo(bar: &T) { ... }
/// ```
pub BORROWED_BOX,
"a borrow of a boxed type"
}
-impl LintPass for TypePass {
- fn get_lints(&self) -> LintArray {
- lint_array!(BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX)
- }
-
- fn name(&self) -> &'static str {
- "Types"
- }
-}
+declare_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX]);
-impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypePass {
+impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types {
fn check_fn(&mut self, cx: &LateContext<'_, '_>, _: FnKind<'_>, decl: &FnDecl, _: &Body, _: Span, id: HirId) {
- // skip trait implementations, see #605
- if let Some(hir::Node::Item(item)) = cx.tcx.hir().find_by_hir_id(cx.tcx.hir().get_parent_item(id)) {
+ // Skip trait implementations; see issue #605.
+ if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
if let ItemKind::Impl(_, _, _, _, Some(..), _, _) = item.node {
return;
}
}
}
-/// Check if `qpath` has last segment with type parameter matching `path`
+/// Checks if `qpath` has last segment with type parameter matching `path`
fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath, path: &[&str]) -> bool {
let last = last_path_segment(qpath);
if_chain! {
_ => None,
});
if let TyKind::Path(ref qpath) = ty.node;
- if let Some(did) = cx.tables.qpath_def(qpath, ty.hir_id).opt_def_id();
- if match_def_path(cx.tcx, did, path);
+ if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id();
+ if match_def_path(cx, did, path);
then {
return true;
}
/// local bindings should only be checked for the `BORROWED_BOX` lint.
#[allow(clippy::too_many_lines)]
fn check_ty(cx: &LateContext<'_, '_>, hir_ty: &hir::Ty, is_local: bool) {
- if in_macro(hir_ty.span) {
+ if hir_ty.span.from_expansion() {
return;
}
match hir_ty.node {
TyKind::Path(ref qpath) if !is_local => {
let hir_id = hir_ty.hir_id;
- let def = cx.tables.qpath_def(qpath, hir_id);
- if let Some(def_id) = def.opt_def_id() {
+ let res = qpath_res(cx, qpath, hir_id);
+ if let Some(def_id) = res.opt_def_id() {
if Some(def_id) == cx.tcx.lang_items().owned_box() {
if match_type_parameter(cx, qpath, &paths::VEC) {
span_help_and_lint(
);
return; // don't recurse into the type
}
- } else if match_def_path(cx.tcx, def_id, &paths::VEC) {
+ } else if cx.tcx.is_diagnostic_item(Symbol::intern("vec_type"), def_id) {
if_chain! {
// Get the _ part of Vec<_>
if let Some(ref last) = last_path_segment(qpath).args;
});
// ty is now _ at this point
if let TyKind::Path(ref ty_qpath) = ty.node;
- let def = cx.tables.qpath_def(ty_qpath, ty.hir_id);
- if let Some(def_id) = def.opt_def_id();
+ let res = qpath_res(cx, ty_qpath, ty.hir_id);
+ if let Some(def_id) = res.opt_def_id();
if Some(def_id) == cx.tcx.lang_items().owned_box();
// At this point, we know ty is Box<T>, now get T
if let Some(ref last) = last_path_segment(ty_qpath).args;
}
}
}
- } else if match_def_path(cx.tcx, def_id, &paths::OPTION) {
+ } else if match_def_path(cx, def_id, &paths::OPTION) {
if match_type_parameter(cx, qpath, &paths::OPTION) {
span_lint(
cx,
);
return; // don't recurse into the type
}
- } else if match_def_path(cx.tcx, def_id, &paths::LINKED_LIST) {
+ } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
span_help_and_lint(
cx,
LINKEDLIST,
match mut_ty.ty.node {
TyKind::Path(ref qpath) => {
let hir_id = mut_ty.ty.hir_id;
- let def = cx.tables.qpath_def(qpath, hir_id);
+ let def = qpath_res(cx, qpath, hir_id);
if_chain! {
if let Some(def_id) = def.opt_def_id();
if Some(def_id) == cx.tcx.lang_items().owned_box();
});
then {
if is_any_trait(inner) {
- // Ignore `Box<Any>` types, see #1884 for details.
+ // Ignore `Box<Any>` types; see issue #1884 for details.
return;
}
false
}
-pub struct LetPass;
-
declare_clippy_lint! {
/// **What it does:** Checks for binding a unit value.
///
"creating a let binding to a value of unit type, which usually can't be used afterwards"
}
-impl LintPass for LetPass {
- fn get_lints(&self) -> LintArray {
- lint_array!(LET_UNIT_VALUE)
- }
-
- fn name(&self) -> &'static str {
- "LetUnitValue"
- }
-}
+declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
-impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetPass {
+impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnitValue {
fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt) {
if let StmtKind::Local(ref local) = stmt.node {
if is_unit(cx.tables.pat_ty(&local.pat)) {
- if in_external_macro(cx.sess(), stmt.span) || in_macro(local.pat.span) {
+ if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
return;
}
if higher::is_from_for_desugar(local) {
return;
}
- span_lint(
- cx,
- LET_UNIT_VALUE,
- stmt.span,
- &format!(
- "this let-binding has unit value. Consider omitting `let {} =`",
- snippet(cx, local.pat.span, "..")
- ),
- );
+ span_lint_and_then(cx, LET_UNIT_VALUE, stmt.span, "this let-binding has unit value", |db| {
+ if let Some(expr) = &local.init {
+ let snip = snippet_with_macro_callsite(cx, expr.span, "()");
+ db.span_suggestion(
+ stmt.span,
+ "omit the `let` binding",
+ format!("{};", snip),
+ Applicability::MachineApplicable, // snippet
+ );
+ }
+ });
}
}
}
/// **Known problems:** None.
///
/// **Example:**
- /// ```ignore
+ /// ```rust
+ /// # fn foo() {};
+ /// # fn bar() {};
+ /// # fn baz() {};
/// if {
/// foo();
/// } == {
/// }
/// ```
/// is equal to
- /// ```ignore
+ /// ```rust
+ /// # fn foo() {};
+ /// # fn bar() {};
+ /// # fn baz() {};
/// {
/// foo();
/// bar();
"comparing unit values"
}
-pub struct UnitCmp;
-
-impl LintPass for UnitCmp {
- fn get_lints(&self) -> LintArray {
- lint_array!(UNIT_CMP)
- }
-
- fn name(&self) -> &'static str {
- "UnicCmp"
- }
-}
+declare_lint_pass!(UnitCmp => [UNIT_CMP]);
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
- if in_macro(expr.span) {
+ if expr.span.from_expansion() {
return;
}
if let ExprKind::Binary(ref cmp, ref left, _) = expr.node {
/// **Known problems:** None.
///
/// **Example:**
- /// ```rust
+ /// ```rust,ignore
/// foo({
/// let a = bar();
/// baz(a);
"passing unit to a function"
}
-pub struct UnitArg;
-
-impl LintPass for UnitArg {
- fn get_lints(&self) -> LintArray {
- lint_array!(UNIT_ARG)
- }
-
- fn name(&self) -> &'static str {
- "UnitArg"
- }
-}
+declare_lint_pass!(UnitArg => [UNIT_ARG]);
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
- if in_macro(expr.span) {
+ if expr.span.from_expansion() {
return;
}
}
if_chain! {
let map = &cx.tcx.hir();
- let opt_parent_node = map.find_by_hir_id(map.get_parent_node_by_hir_id(expr.hir_id));
+ let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
if is_questionmark_desugar_marked_call(parent_expr);
then {
}
fn is_questionmark_desugar_marked_call(expr: &Expr) -> bool {
- use syntax_pos::hygiene::CompilerDesugaringKind;
+ use syntax_pos::hygiene::DesugaringKind;
if let ExprKind::Call(ref callee, _) = expr.node {
- callee.span.is_compiler_desugaring(CompilerDesugaringKind::QuestionMark)
+ callee.span.is_desugaring(DesugaringKind::QuestionMark)
} else {
false
}
}
}
-pub struct CastPass;
-
declare_clippy_lint! {
/// **What it does:** Checks for casts from any numerical to a float type where
/// the receiving type cannot store all values from the original type without
///
/// **Example:**
/// ```rust
- /// let x = u64::MAX;
- /// x as f64
+ /// let x = std::u64::MAX;
+ /// x as f64;
/// ```
pub CAST_PRECISION_LOSS,
pedantic,
- "casts that cause loss of precision, e.g. `x as f32` where `x: u64`"
+ "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
}
declare_clippy_lint! {
/// **Example:**
/// ```rust
/// let y: i8 = -1;
- /// y as u128 // will return 18446744073709551615
+ /// y as u128; // will return 18446744073709551615
/// ```
pub CAST_SIGN_LOSS,
pedantic,
- "casts from signed types to unsigned types, e.g. `x as u32` where `x: i32`"
+ "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
}
declare_clippy_lint! {
- /// **What it does:** Checks for on casts between numerical types that may
+ /// **What it does:** Checks for casts between numerical types that may
/// truncate large values. This is expected behavior, so the cast is `Allow` by
/// default.
///
/// ```
pub CAST_POSSIBLE_TRUNCATION,
pedantic,
- "casts that may cause truncation of the value, e.g. `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
+ "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
}
declare_clippy_lint! {
/// **What it does:** Checks for casts from an unsigned type to a signed type of
/// the same size. Performing such a cast is a 'no-op' for the compiler,
- /// i.e. nothing is changed at the bit level, and the binary representation of
+ /// i.e., nothing is changed at the bit level, and the binary representation of
/// the value is reinterpreted. This can cause wrapping if the value is too big
/// for the target signed type. However, the cast works as defined, so this lint
/// is `Allow` by default.
///
/// **Example:**
/// ```rust
- /// u32::MAX as i32 // will yield a value of `-1`
+ /// std::u32::MAX as i32; // will yield a value of `-1`
/// ```
pub CAST_POSSIBLE_WRAP,
pedantic,
- "casts that may cause wrapping around the value, e.g. `x as i32` where `x: u32` and `x > i32::MAX`"
+ "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
}
declare_clippy_lint! {
- /// **What it does:** Checks for on casts between numerical types that may
+ /// **What it does:** Checks for casts between numerical types that may
/// be replaced by safe conversion functions.
///
/// **Why is this bad?** Rust's `as` keyword will perform many kinds of
/// }
/// ```
pub CAST_LOSSLESS,
- complexity,
- "casts using `as` that are known to be lossless, e.g. `x as u64` where `x: u8`"
+ pedantic,
+ "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
}
declare_clippy_lint! {
///
/// **Example:**
/// ```rust
- /// let _ = 2i32 as i32
+ /// let _ = 2i32 as i32;
/// ```
pub UNNECESSARY_CAST,
complexity,
- "cast to the same type, e.g. `x as i32` where `x: i32`"
+ "cast to the same type, e.g., `x as i32` where `x: i32`"
}
declare_clippy_lint! {
/// **Why is this bad?** Dereferencing the resulting pointer may be undefined
/// behavior.
///
- /// **Known problems:** None.
+ /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
+ /// on the resulting pointer is fine.
///
/// **Example:**
/// ```rust
///
/// **Example**
///
- /// ```ignore
+ /// ```rust
/// // Bad
- /// fn fun() -> i32 {}
+ /// fn fun() -> i32 { 1 }
/// let a = fun as i64;
///
/// // Good
- /// fn fun2() -> i32 {}
+ /// fn fun2() -> i32 { 1 }
/// let a = fun2 as usize;
/// ```
pub FN_TO_NUMERIC_CAST,
/// Returns the size in bits of an integral type.
/// Will return 0 if the type is not an int or uint variant
-fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_, '_, '_>) -> u64 {
+fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
match typ.sty {
ty::Int(i) => match i {
IntTy::Isize => tcx.data_layout.pointer_size.bits(),
CAST_LOSSLESS,
expr.span,
&format!(
- "casting {} to {} may become silently lossy if types change",
+ "casting {} to {} may become silently lossy if you later change the type",
cast_from, cast_to
),
"try",
}
}
-impl LintPass for CastPass {
- fn get_lints(&self) -> LintArray {
- lint_array!(
- CAST_PRECISION_LOSS,
- CAST_SIGN_LOSS,
- CAST_POSSIBLE_TRUNCATION,
- CAST_POSSIBLE_WRAP,
- CAST_LOSSLESS,
- UNNECESSARY_CAST,
- CAST_PTR_ALIGNMENT,
- FN_TO_NUMERIC_CAST,
- FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
- )
- }
-
- fn name(&self) -> &'static str {
- "Casts"
- }
-}
+declare_lint_pass!(Casts => [
+ CAST_PRECISION_LOSS,
+ CAST_SIGN_LOSS,
+ CAST_POSSIBLE_TRUNCATION,
+ CAST_POSSIBLE_WRAP,
+ CAST_LOSSLESS,
+ UNNECESSARY_CAST,
+ CAST_PTR_ALIGNMENT,
+ FN_TO_NUMERIC_CAST,
+ FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
+]);
// Check if the given type is either `core::ffi::c_void` or
// one of the platform specific `libc::<platform>::c_void` of libc.
-fn is_c_void(tcx: TyCtxt<'_, '_, '_>, ty: Ty<'_>) -> bool {
+fn is_c_void(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
if let ty::Adt(adt, _) = ty.sty {
- let mut apb = AbsolutePathBuffer { names: vec![] };
- tcx.push_item_path(&mut apb, adt.did, false);
+ let names = cx.get_def_path(adt.did);
- if apb.names.is_empty() {
+ if names.is_empty() {
return false;
}
- if apb.names[0] == "libc" || apb.names[0] == "core" && *apb.names.last().unwrap() == "c_void" {
+ if names[0] == sym!(libc) || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
return true;
}
}
false
}
-impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CastPass {
+/// Returns the mantissa bits wide of a fp type.
+/// Will return 0 if the type is not a fp
+fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
+ match typ.sty {
+ ty::Float(FloatTy::F32) => 23,
+ ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
+ _ => 0,
+ }
+}
+
+impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
+ if expr.span.from_expansion() {
+ return;
+ }
if let ExprKind::Cast(ref ex, _) = expr.node {
let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
if let ExprKind::Lit(ref lit) = ex.node {
- use syntax::ast::{LitIntType, LitKind};
+ if let LitKind::Int(n, _) = lit.node {
+ if cast_to.is_floating_point() {
+ let from_nbits = 128 - n.leading_zeros();
+ let to_nbits = fp_ty_mantissa_nbits(cast_to);
+ if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits {
+ span_lint_and_sugg(
+ cx,
+ UNNECESSARY_CAST,
+ expr.span,
+ &format!("casting integer literal to {} is unnecessary", cast_to),
+ "try",
+ format!("{}_{}", n, cast_to),
+ Applicability::MachineApplicable,
+ );
+ return;
+ }
+ }
+ }
match lit.node {
LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::FloatUnsuffixed(_) => {},
_ => {
}
}
if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
- match (cast_from.is_integral(), cast_to.is_integral()) {
- (true, false) => {
- let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
- let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.sty {
- 32
- } else {
- 64
- };
- if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
- span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
- }
- if from_nbits < to_nbits {
- span_lossless_lint(cx, expr, ex, cast_from, cast_to);
- }
- },
- (false, true) => {
- span_lint(
- cx,
- CAST_POSSIBLE_TRUNCATION,
- expr.span,
- &format!("casting {} to {} may truncate the value", cast_from, cast_to),
- );
- if !cast_to.is_signed() {
- span_lint(
- cx,
- CAST_SIGN_LOSS,
- expr.span,
- &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
- );
- }
- },
- (true, true) => {
- check_loss_of_sign(cx, expr, ex, cast_from, cast_to);
- check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
- check_lossless(cx, expr, ex, cast_from, cast_to);
- },
- (false, false) => {
- if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty) {
- span_lint(
- cx,
- CAST_POSSIBLE_TRUNCATION,
- expr.span,
- "casting f64 to f32 may truncate the value",
- );
- }
- if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty) {
- span_lossless_lint(cx, expr, ex, cast_from, cast_to);
- }
- },
- }
+ lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
}
- if_chain! {
- if let ty::RawPtr(from_ptr_ty) = &cast_from.sty;
- if let ty::RawPtr(to_ptr_ty) = &cast_to.sty;
- if let Some(from_align) = cx.layout_of(from_ptr_ty.ty).ok().map(|a| a.align.abi);
- if let Some(to_align) = cx.layout_of(to_ptr_ty.ty).ok().map(|a| a.align.abi);
- if from_align < to_align;
- // with c_void, we inherently need to trust the user
- if !is_c_void(cx.tcx, from_ptr_ty.ty);
- then {
- span_lint(
- cx,
- CAST_PTR_ALIGNMENT,
- expr.span,
- &format!("casting from `{}` to a more-strictly-aligned pointer (`{}`)", cast_from, cast_to)
- );
- }
+ lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
+ }
+ }
+}
+
+fn lint_numeric_casts<'tcx>(
+ cx: &LateContext<'_, 'tcx>,
+ expr: &Expr,
+ cast_expr: &Expr,
+ cast_from: Ty<'tcx>,
+ cast_to: Ty<'tcx>,
+) {
+ match (cast_from.is_integral(), cast_to.is_integral()) {
+ (true, false) => {
+ let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
+ let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.sty {
+ 32
+ } else {
+ 64
+ };
+ if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
+ span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
+ }
+ if from_nbits < to_nbits {
+ span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
+ }
+ },
+ (false, true) => {
+ span_lint(
+ cx,
+ CAST_POSSIBLE_TRUNCATION,
+ expr.span,
+ &format!("casting {} to {} may truncate the value", cast_from, cast_to),
+ );
+ if !cast_to.is_signed() {
+ span_lint(
+ cx,
+ CAST_SIGN_LOSS,
+ expr.span,
+ &format!("casting {} to {} may lose the sign of the value", cast_from, cast_to),
+ );
+ }
+ },
+ (true, true) => {
+ check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
+ check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
+ check_lossless(cx, expr, cast_expr, cast_from, cast_to);
+ },
+ (false, false) => {
+ if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.sty, &cast_to.sty) {
+ span_lint(
+ cx,
+ CAST_POSSIBLE_TRUNCATION,
+ expr.span,
+ "casting f64 to f32 may truncate the value",
+ );
+ }
+ if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.sty, &cast_to.sty) {
+ span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
}
+ },
+ }
+}
+
+fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
+ if_chain! {
+ if let ty::RawPtr(from_ptr_ty) = &cast_from.sty;
+ if let ty::RawPtr(to_ptr_ty) = &cast_to.sty;
+ if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
+ if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
+ if from_layout.align.abi < to_layout.align.abi;
+ // with c_void, we inherently need to trust the user
+ if !is_c_void(cx, from_ptr_ty.ty);
+ // when casting from a ZST, we don't know enough to properly lint
+ if !from_layout.is_zst();
+ then {
+ span_lint(
+ cx,
+ CAST_PTR_ALIGNMENT,
+ expr.span,
+ &format!(
+ "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
+ cast_from,
+ cast_to,
+ from_layout.align.abi.bytes(),
+ to_layout.align.abi.bytes(),
+ ),
+ );
}
}
}
}
match cast_from.sty {
ty::FnDef(..) | ty::FnPtr(_) => {
- let mut applicability = Applicability::MachineApplicable;
+ let mut applicability = Applicability::MaybeIncorrect;
let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
///
/// **Example:**
/// ```rust
+ /// # use std::rc::Rc;
/// struct Foo {
/// inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
/// }
"usage of very complex types that might be better factored into `type` definitions"
}
-pub struct TypeComplexityPass {
+pub struct TypeComplexity {
threshold: u64,
}
-impl TypeComplexityPass {
+impl TypeComplexity {
pub fn new(threshold: u64) -> Self {
Self { threshold }
}
}
-impl LintPass for TypeComplexityPass {
- fn get_lints(&self) -> LintArray {
- lint_array!(TYPE_COMPLEXITY)
- }
-
- fn name(&self) -> &'static str {
- "TypeComplexityPass"
- }
-}
+impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
-impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexityPass {
+impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity {
fn check_fn(
&mut self,
cx: &LateContext<'a, 'tcx>,
fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
match item.node {
- ImplItemKind::Const(ref ty, _) | ImplItemKind::Type(ref ty) => self.check_type(cx, ty),
+ ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
// methods are covered by check_fn
_ => (),
}
}
}
-impl<'a, 'tcx> TypeComplexityPass {
+impl<'a, 'tcx> TypeComplexity {
fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl) {
for arg in &decl.inputs {
self.check_type(cx, arg);
}
fn check_type(&self, cx: &LateContext<'_, '_>, ty: &hir::Ty) {
- if in_macro(ty.span) {
+ if ty.span.from_expansion() {
return;
}
let score = {
/// **Known problems:** None.
///
/// **Example:**
- /// ```rust
+ /// ```rust,ignore
/// 'x' as u8
/// ```
///
/// A better version, using the byte literal:
///
- /// ```rust
+ /// ```rust,ignore
/// b'x'
/// ```
pub CHAR_LIT_AS_U8,
complexity,
- "casting a character literal to u8"
+ "casting a character literal to u8 truncates"
}
-pub struct CharLitAsU8;
-
-impl LintPass for CharLitAsU8 {
- fn get_lints(&self) -> LintArray {
- lint_array!(CHAR_LIT_AS_U8)
- }
-
- fn name(&self) -> &'static str {
- "CharLiteralAsU8"
- }
-}
+declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
- use syntax::ast::{LitKind, UintTy};
-
- if let ExprKind::Cast(ref e, _) = expr.node {
- if let ExprKind::Lit(ref l) = e.node {
- if let LitKind::Char(_) = l.node {
- if ty::Uint(UintTy::U8) == cx.tables.expr_ty(expr).sty && !in_macro(expr.span) {
- let msg = "casting character literal to u8. `char`s \
- are 4 bytes wide in rust, so casting to u8 \
- truncates them";
- let help = format!(
- "Consider using a byte literal instead:\nb{}",
- snippet(cx, e.span, "'x'")
- );
- span_help_and_lint(cx, CHAR_LIT_AS_U8, expr.span, msg, &help);
- }
- }
+ if_chain! {
+ if !expr.span.from_expansion();
+ if let ExprKind::Cast(e, _) = &expr.node;
+ if let ExprKind::Lit(l) = &e.node;
+ if let LitKind::Char(c) = l.node;
+ if ty::Uint(UintTy::U8) == cx.tables.expr_ty(expr).sty;
+ then {
+ let mut applicability = Applicability::MachineApplicable;
+ let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
+
+ span_lint_and_then(
+ cx,
+ CHAR_LIT_AS_U8,
+ expr.span,
+ "casting a character literal to `u8` truncates",
+ |db| {
+ db.note("`char` is four bytes wide, but `u8` is a single byte");
+
+ if c.is_ascii() {
+ db.span_suggestion(
+ expr.span,
+ "use a byte literal instead",
+ format!("b{}", snippet),
+ applicability,
+ );
+ }
+ });
}
}
}
/// checked.
///
/// **Why is this bad?** An expression like `min <= x` may misleadingly imply
- /// that is is possible for `x` to be less than the minimum. Expressions like
+ /// that it is possible for `x` to be less than the minimum. Expressions like
/// `max < x` are probably mistakes.
///
/// **Known problems:** For `usize` the size of the current compile target will
- /// be assumed (e.g. 64 bits on 64 bit systems). This means code that uses such
+ /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
/// a comparison to detect target pointer width will trigger this lint. One can
/// use `mem::sizeof` and compare its value or conditional compilation
/// attributes
/// like `#[cfg(target_pointer_width = "64")] ..` instead.
///
/// **Example:**
- /// ```ignore
- /// vec.len() <= 0
- /// 100 > std::i32::MAX
+ ///
+ /// ```rust
+ /// let vec: Vec<isize> = vec![];
+ /// if vec.len() <= 0 {}
+ /// if 100 > std::i32::MAX {}
/// ```
pub ABSURD_EXTREME_COMPARISONS,
correctness,
"a comparison with a maximum or minimum value that is always true or false"
}
-pub struct AbsurdExtremeComparisons;
-
-impl LintPass for AbsurdExtremeComparisons {
- fn get_lints(&self) -> LintArray {
- lint_array!(ABSURD_EXTREME_COMPARISONS)
- }
-
- fn name(&self) -> &'static str {
- "AbsurdExtremeComparisons"
- }
-}
+declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
enum ExtremeType {
Minimum,
if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.node {
if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
- if !in_macro(expr.span) {
+ if !expr.span.from_expansion() {
let msg = "this comparison involving the minimum or maximum element for this \
type contains a case that is always true or always false";
///
/// **Example:**
/// ```rust
- /// let x : u8 = ...; (x as u32) > 300
+ /// let x: u8 = 1;
+ /// (x as u32) > 300;
/// ```
pub INVALID_UPCAST_COMPARISONS,
pedantic,
"a comparison involving an upcast which is always true or false"
}
-pub struct InvalidUpcastComparisons;
-
-impl LintPass for InvalidUpcastComparisons {
- fn get_lints(&self) -> LintArray {
- lint_array!(INVALID_UPCAST_COMPARISONS)
- }
-
- fn name(&self) -> &'static str {
- "InvalidUpcastComparisons"
- }
-}
+declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
#[derive(Copy, Clone, Debug, Eq)]
enum FullInt {
impl PartialOrd for FullInt {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(match (self, other) {
- (&FullInt::S(s), &FullInt::S(o)) => s.cmp(&o),
- (&FullInt::U(s), &FullInt::U(o)) => s.cmp(&o),
- (&FullInt::S(s), &FullInt::U(o)) => Self::cmp_s_u(s, o),
- (&FullInt::U(s), &FullInt::S(o)) => Self::cmp_s_u(o, s).reverse(),
+ (&Self::S(s), &Self::S(o)) => s.cmp(&o),
+ (&Self::U(s), &Self::U(o)) => s.cmp(&o),
+ (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
+ (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
})
}
}
fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr) -> Option<(FullInt, FullInt)> {
use std::*;
- use syntax::ast::{IntTy, UintTy};
if let ExprKind::Cast(ref cast_exp, _) = expr.node {
let pre_cast_ty = cx.tables.expr_ty(cast_exp);
/// pieces of code, possibly including external crates.
///
/// **Example:**
- /// ```ignore
- /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { ... }
+ /// ```rust
+ /// # use std::collections::HashMap;
+ /// # use std::hash::{Hash, BuildHasher};
+ /// # trait Serialize {};
+ /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
+ ///
+ /// pub fn foo(map: &mut HashMap<i32, i32>) { }
+ /// ```
+ /// could be rewritten as
+ /// ```rust
+ /// # use std::collections::HashMap;
+ /// # use std::hash::{Hash, BuildHasher};
+ /// # trait Serialize {};
+ /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
///
- /// pub foo(map: &mut HashMap<i32, i32>) { .. }
+ /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
/// ```
pub IMPLICIT_HASHER,
style,
"missing generalization over different hashers"
}
-pub struct ImplicitHasher;
-
-impl LintPass for ImplicitHasher {
- fn get_lints(&self) -> LintArray {
- lint_array!(IMPLICIT_HASHER)
- }
-
- fn name(&self) -> &'static str {
- "ImplicitHasher"
- }
-}
+declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
#[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
}
}
- if !cx.access_levels.is_exported(cx.tcx.hir().hir_to_node_id(item.hir_id)) {
+ if !cx.access_levels.is_exported(item.hir_id) {
return;
}
vis.visit_ty(ty);
for target in &vis.found {
+ if in_external_macro(cx.sess(), generics.span) {
+ continue;
+ }
let generics_suggestion_span = generics.span.substitute_dummy({
- let pos = snippet_opt(cx, item.span.until(body.arguments[0].pat.span))
+ let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
.and_then(|snip| {
let i = snip.find("fn")?;
Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
}
}
-struct ImplicitHasherTypeVisitor<'a, 'tcx: 'a> {
+struct ImplicitHasherTypeVisitor<'a, 'tcx> {
cx: &'a LateContext<'a, 'tcx>,
found: Vec<ImplicitHasherType<'tcx>>,
}
-impl<'a, 'tcx: 'a> ImplicitHasherTypeVisitor<'a, 'tcx> {
+impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
Self { cx, found: vec![] }
}
}
-impl<'a, 'tcx: 'a> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
+impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
fn visit_ty(&mut self, t: &'tcx hir::Ty) {
if let Some(target) = ImplicitHasherType::new(self.cx, t) {
self.found.push(target);
}
/// Looks for default-hasher-dependent constructors like `HashMap::new`.
-struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx: 'a + 'b> {
+struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
cx: &'a LateContext<'a, 'tcx>,
body: &'a TypeckTables<'tcx>,
target: &'b ImplicitHasherType<'tcx>,
suggestions: BTreeMap<Span, String>,
}
-impl<'a, 'b, 'tcx: 'a + 'b> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
+impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
Self {
cx,
}
}
-impl<'a, 'b, 'tcx: 'a + 'b> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
+impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
fn visit_body(&mut self, body: &'tcx Body) {
let prev_body = self.body;
self.body = self.cx.tcx.body_tables(body.id());
}
if match_path(ty_path, &paths::HASHMAP) {
- if method.ident.name == "new" {
+ if method.ident.name == sym!(new) {
self.suggestions
.insert(e.span, "HashMap::default()".to_string());
- } else if method.ident.name == "with_capacity" {
+ } else if method.ident.name == sym!(with_capacity) {
self.suggestions.insert(
e.span,
format!(
);
}
} else if match_path(ty_path, &paths::HASHSET) {
- if method.ident.name == "new" {
+ if method.ident.name == sym!(new) {
self.suggestions
.insert(e.span, "HashSet::default()".to_string());
- } else if method.ident.name == "with_capacity" {
+ } else if method.ident.name == sym!(with_capacity) {
self.suggestions.insert(
e.span,
format!(
/// **Known problems:** None.
///
/// **Example:**
- /// ```ignore
+ /// ```rust,ignore
/// fn x(r: &i32) {
/// unsafe {
/// *(r as *const _ as *mut _) += 1;
///
/// Instead consider using interior mutability types.
///
- /// ```ignore
+ /// ```rust
+ /// use std::cell::UnsafeCell;
+ ///
/// fn x(r: &UnsafeCell<i32>) {
/// unsafe {
/// *r.get() += 1;
"a cast of reference to a mutable pointer"
}
-pub struct RefToMut;
-
-impl LintPass for RefToMut {
- fn get_lints(&self) -> LintArray {
- lint_array!(CAST_REF_TO_MUT)
- }
-
- fn name(&self) -> &'static str {
- "RefToMut"
- }
-}
+declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {