]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/types.rs
Fix NAN comparison lint to use assoc NAN
[rust.git] / clippy_lints / src / types.rs
1 #![allow(rustc::default_hash_types)]
2
3 use std::borrow::Cow;
4 use std::cmp::Ordering;
5 use std::collections::BTreeMap;
6
7 use if_chain::if_chain;
8 use rustc_ast::ast::{FloatTy, IntTy, LitFloatType, LitIntType, LitKind, UintTy};
9 use rustc_errors::{Applicability, DiagnosticBuilder};
10 use rustc_hir as hir;
11 use rustc_hir::intravisit::{walk_body, walk_expr, walk_ty, FnKind, NestedVisitorMap, Visitor};
12 use rustc_hir::{
13     BinOpKind, Body, Expr, ExprKind, FnDecl, FnRetTy, FnSig, GenericArg, GenericParamKind, HirId, ImplItem,
14     ImplItemKind, Item, ItemKind, Lifetime, Local, MatchSource, MutTy, Mutability, QPath, Stmt, StmtKind, TraitFn,
15     TraitItem, TraitItemKind, TyKind, UnOp,
16 };
17 use rustc_lint::{LateContext, LateLintPass, LintContext};
18 use rustc_middle::hir::map::Map;
19 use rustc_middle::lint::in_external_macro;
20 use rustc_middle::ty::{self, InferTy, Ty, TyCtxt, TypeckTables};
21 use rustc_session::{declare_lint_pass, declare_tool_lint, impl_lint_pass};
22 use rustc_span::hygiene::{ExpnKind, MacroKind};
23 use rustc_span::source_map::Span;
24 use rustc_span::symbol::{sym, Symbol};
25 use rustc_target::abi::LayoutOf;
26 use rustc_target::spec::abi::Abi;
27 use rustc_typeck::hir_ty_to_ty;
28
29 use crate::consts::{constant, Constant};
30 use crate::utils::paths;
31 use crate::utils::{
32     clip, comparisons, differing_macro_contexts, higher, in_constant, int_bits, last_path_segment, match_def_path,
33     match_path, method_chain_args, multispan_sugg, numeric_literal::NumericLiteral, qpath_res, same_tys, sext, snippet,
34     snippet_opt, snippet_with_applicability, snippet_with_macro_callsite, span_lint, span_lint_and_help,
35     span_lint_and_sugg, span_lint_and_then, unsext,
36 };
37
38 declare_clippy_lint! {
39     /// **What it does:** Checks for use of `Box<Vec<_>>` anywhere in the code.
40     ///
41     /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
42     /// the heap. So if you `Box` it, you just add another level of indirection
43     /// without any benefit whatsoever.
44     ///
45     /// **Known problems:** None.
46     ///
47     /// **Example:**
48     /// ```rust,ignore
49     /// struct X {
50     ///     values: Box<Vec<Foo>>,
51     /// }
52     /// ```
53     ///
54     /// Better:
55     ///
56     /// ```rust,ignore
57     /// struct X {
58     ///     values: Vec<Foo>,
59     /// }
60     /// ```
61     pub BOX_VEC,
62     perf,
63     "usage of `Box<Vec<T>>`, vector elements are already on the heap"
64 }
65
66 declare_clippy_lint! {
67     /// **What it does:** Checks for use of `Vec<Box<T>>` where T: Sized anywhere in the code.
68     ///
69     /// **Why is this bad?** `Vec` already keeps its contents in a separate area on
70     /// the heap. So if you `Box` its contents, you just add another level of indirection.
71     ///
72     /// **Known problems:** Vec<Box<T: Sized>> makes sense if T is a large type (see #3530,
73     /// 1st comment).
74     ///
75     /// **Example:**
76     /// ```rust
77     /// struct X {
78     ///     values: Vec<Box<i32>>,
79     /// }
80     /// ```
81     ///
82     /// Better:
83     ///
84     /// ```rust
85     /// struct X {
86     ///     values: Vec<i32>,
87     /// }
88     /// ```
89     pub VEC_BOX,
90     complexity,
91     "usage of `Vec<Box<T>>` where T: Sized, vector elements are already on the heap"
92 }
93
94 declare_clippy_lint! {
95     /// **What it does:** Checks for use of `Option<Option<_>>` in function signatures and type
96     /// definitions
97     ///
98     /// **Why is this bad?** `Option<_>` represents an optional value. `Option<Option<_>>`
99     /// represents an optional optional value which is logically the same thing as an optional
100     /// value but has an unneeded extra level of wrapping.
101     ///
102     /// If you have a case where `Some(Some(_))`, `Some(None)` and `None` are distinct cases,
103     /// consider a custom `enum` instead, with clear names for each case.
104     ///
105     /// **Known problems:** None.
106     ///
107     /// **Example**
108     /// ```rust
109     /// fn get_data() -> Option<Option<u32>> {
110     ///     None
111     /// }
112     /// ```
113     ///
114     /// Better:
115     ///
116     /// ```rust
117     /// pub enum Contents {
118     ///     Data(Vec<u8>), // Was Some(Some(Vec<u8>))
119     ///     NotYetFetched, // Was Some(None)
120     ///     None,          // Was None
121     /// }
122     ///
123     /// fn get_data() -> Contents {
124     ///     Contents::None
125     /// }
126     /// ```
127     pub OPTION_OPTION,
128     pedantic,
129     "usage of `Option<Option<T>>`"
130 }
131
132 declare_clippy_lint! {
133     /// **What it does:** Checks for usage of any `LinkedList`, suggesting to use a
134     /// `Vec` or a `VecDeque` (formerly called `RingBuf`).
135     ///
136     /// **Why is this bad?** Gankro says:
137     ///
138     /// > The TL;DR of `LinkedList` is that it's built on a massive amount of
139     /// pointers and indirection.
140     /// > It wastes memory, it has terrible cache locality, and is all-around slow.
141     /// `RingBuf`, while
142     /// > "only" amortized for push/pop, should be faster in the general case for
143     /// almost every possible
144     /// > workload, and isn't even amortized at all if you can predict the capacity
145     /// you need.
146     /// >
147     /// > `LinkedList`s are only really good if you're doing a lot of merging or
148     /// splitting of lists.
149     /// > This is because they can just mangle some pointers instead of actually
150     /// copying the data. Even
151     /// > if you're doing a lot of insertion in the middle of the list, `RingBuf`
152     /// can still be better
153     /// > because of how expensive it is to seek to the middle of a `LinkedList`.
154     ///
155     /// **Known problems:** False positives – the instances where using a
156     /// `LinkedList` makes sense are few and far between, but they can still happen.
157     ///
158     /// **Example:**
159     /// ```rust
160     /// # use std::collections::LinkedList;
161     /// let x: LinkedList<usize> = LinkedList::new();
162     /// ```
163     pub LINKEDLIST,
164     pedantic,
165     "usage of LinkedList, usually a vector is faster, or a more specialized data structure like a `VecDeque`"
166 }
167
168 declare_clippy_lint! {
169     /// **What it does:** Checks for use of `&Box<T>` anywhere in the code.
170     ///
171     /// **Why is this bad?** Any `&Box<T>` can also be a `&T`, which is more
172     /// general.
173     ///
174     /// **Known problems:** None.
175     ///
176     /// **Example:**
177     /// ```rust,ignore
178     /// fn foo(bar: &Box<T>) { ... }
179     /// ```
180     ///
181     /// Better:
182     ///
183     /// ```rust,ignore
184     /// fn foo(bar: &T) { ... }
185     /// ```
186     pub BORROWED_BOX,
187     complexity,
188     "a borrow of a boxed type"
189 }
190
191 declare_clippy_lint! {
192     /// **What it does:** Checks for use of redundant allocations anywhere in the code.
193     ///
194     /// **Why is this bad?** Expressions such as `Rc<&T>`, `Rc<Rc<T>>`, `Rc<Box<T>>`, `Box<&T>`
195     /// add an unnecessary level of indirection.
196     ///
197     /// **Known problems:** None.
198     ///
199     /// **Example:**
200     /// ```rust
201     /// # use std::rc::Rc;
202     /// fn foo(bar: Rc<&usize>) {}
203     /// ```
204     ///
205     /// Better:
206     ///
207     /// ```rust
208     /// fn foo(bar: &usize) {}
209     /// ```
210     pub REDUNDANT_ALLOCATION,
211     perf,
212     "redundant allocation"
213 }
214
215 pub struct Types {
216     vec_box_size_threshold: u64,
217 }
218
219 impl_lint_pass!(Types => [BOX_VEC, VEC_BOX, OPTION_OPTION, LINKEDLIST, BORROWED_BOX, REDUNDANT_ALLOCATION]);
220
221 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Types {
222     fn check_fn(
223         &mut self,
224         cx: &LateContext<'_, '_>,
225         _: FnKind<'_>,
226         decl: &FnDecl<'_>,
227         _: &Body<'_>,
228         _: Span,
229         id: HirId,
230     ) {
231         // Skip trait implementations; see issue #605.
232         if let Some(hir::Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_item(id)) {
233             if let ItemKind::Impl { of_trait: Some(_), .. } = item.kind {
234                 return;
235             }
236         }
237
238         self.check_fn_decl(cx, decl);
239     }
240
241     fn check_struct_field(&mut self, cx: &LateContext<'_, '_>, field: &hir::StructField<'_>) {
242         self.check_ty(cx, &field.ty, false);
243     }
244
245     fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &TraitItem<'_>) {
246         match item.kind {
247             TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_ty(cx, ty, false),
248             TraitItemKind::Fn(ref sig, _) => self.check_fn_decl(cx, &sig.decl),
249             _ => (),
250         }
251     }
252
253     fn check_local(&mut self, cx: &LateContext<'_, '_>, local: &Local<'_>) {
254         if let Some(ref ty) = local.ty {
255             self.check_ty(cx, ty, true);
256         }
257     }
258 }
259
260 /// Checks if `qpath` has last segment with type parameter matching `path`
261 fn match_type_parameter(cx: &LateContext<'_, '_>, qpath: &QPath<'_>, path: &[&str]) -> Option<Span> {
262     let last = last_path_segment(qpath);
263     if_chain! {
264         if let Some(ref params) = last.args;
265         if !params.parenthesized;
266         if let Some(ty) = params.args.iter().find_map(|arg| match arg {
267             GenericArg::Type(ty) => Some(ty),
268             _ => None,
269         });
270         if let TyKind::Path(ref qpath) = ty.kind;
271         if let Some(did) = qpath_res(cx, qpath, ty.hir_id).opt_def_id();
272         if match_def_path(cx, did, path);
273         then {
274             return Some(ty.span);
275         }
276     }
277     None
278 }
279
280 fn match_borrows_parameter(_cx: &LateContext<'_, '_>, qpath: &QPath<'_>) -> Option<Span> {
281     let last = last_path_segment(qpath);
282     if_chain! {
283         if let Some(ref params) = last.args;
284         if !params.parenthesized;
285         if let Some(ty) = params.args.iter().find_map(|arg| match arg {
286             GenericArg::Type(ty) => Some(ty),
287             _ => None,
288         });
289         if let TyKind::Rptr(..) = ty.kind;
290         then {
291             return Some(ty.span);
292         }
293     }
294     None
295 }
296
297 impl Types {
298     pub fn new(vec_box_size_threshold: u64) -> Self {
299         Self { vec_box_size_threshold }
300     }
301
302     fn check_fn_decl(&mut self, cx: &LateContext<'_, '_>, decl: &FnDecl<'_>) {
303         for input in decl.inputs {
304             self.check_ty(cx, input, false);
305         }
306
307         if let FnRetTy::Return(ref ty) = decl.output {
308             self.check_ty(cx, ty, false);
309         }
310     }
311
312     /// Recursively check for `TypePass` lints in the given type. Stop at the first
313     /// lint found.
314     ///
315     /// The parameter `is_local` distinguishes the context of the type; types from
316     /// local bindings should only be checked for the `BORROWED_BOX` lint.
317     #[allow(clippy::too_many_lines)]
318     #[allow(clippy::cognitive_complexity)]
319     fn check_ty(&mut self, cx: &LateContext<'_, '_>, hir_ty: &hir::Ty<'_>, is_local: bool) {
320         if hir_ty.span.from_expansion() {
321             return;
322         }
323         match hir_ty.kind {
324             TyKind::Path(ref qpath) if !is_local => {
325                 let hir_id = hir_ty.hir_id;
326                 let res = qpath_res(cx, qpath, hir_id);
327                 if let Some(def_id) = res.opt_def_id() {
328                     if Some(def_id) == cx.tcx.lang_items().owned_box() {
329                         if let Some(span) = match_borrows_parameter(cx, qpath) {
330                             span_lint_and_sugg(
331                                 cx,
332                                 REDUNDANT_ALLOCATION,
333                                 hir_ty.span,
334                                 "usage of `Box<&T>`",
335                                 "try",
336                                 snippet(cx, span, "..").to_string(),
337                                 Applicability::MachineApplicable,
338                             );
339                             return; // don't recurse into the type
340                         }
341                         if match_type_parameter(cx, qpath, &paths::VEC).is_some() {
342                             span_lint_and_help(
343                                 cx,
344                                 BOX_VEC,
345                                 hir_ty.span,
346                                 "you seem to be trying to use `Box<Vec<T>>`. Consider using just `Vec<T>`",
347                                 "`Vec<T>` is already on the heap, `Box<Vec<T>>` makes an extra allocation.",
348                             );
349                             return; // don't recurse into the type
350                         }
351                     } else if Some(def_id) == cx.tcx.lang_items().rc() {
352                         if let Some(span) = match_type_parameter(cx, qpath, &paths::RC) {
353                             span_lint_and_sugg(
354                                 cx,
355                                 REDUNDANT_ALLOCATION,
356                                 hir_ty.span,
357                                 "usage of `Rc<Rc<T>>`",
358                                 "try",
359                                 snippet(cx, span, "..").to_string(),
360                                 Applicability::MachineApplicable,
361                             );
362                             return; // don't recurse into the type
363                         }
364                         if let Some(span) = match_type_parameter(cx, qpath, &paths::BOX) {
365                             span_lint_and_sugg(
366                                 cx,
367                                 REDUNDANT_ALLOCATION,
368                                 hir_ty.span,
369                                 "usage of `Rc<Box<T>>`",
370                                 "try",
371                                 snippet(cx, span, "..").to_string(),
372                                 Applicability::MachineApplicable,
373                             );
374                             return; // don't recurse into the type
375                         }
376                         if let Some(span) = match_borrows_parameter(cx, qpath) {
377                             span_lint_and_sugg(
378                                 cx,
379                                 REDUNDANT_ALLOCATION,
380                                 hir_ty.span,
381                                 "usage of `Rc<&T>`",
382                                 "try",
383                                 snippet(cx, span, "..").to_string(),
384                                 Applicability::MachineApplicable,
385                             );
386                             return; // don't recurse into the type
387                         }
388                     } else if cx.tcx.is_diagnostic_item(Symbol::intern("vec_type"), def_id) {
389                         if_chain! {
390                             // Get the _ part of Vec<_>
391                             if let Some(ref last) = last_path_segment(qpath).args;
392                             if let Some(ty) = last.args.iter().find_map(|arg| match arg {
393                                 GenericArg::Type(ty) => Some(ty),
394                                 _ => None,
395                             });
396                             // ty is now _ at this point
397                             if let TyKind::Path(ref ty_qpath) = ty.kind;
398                             let res = qpath_res(cx, ty_qpath, ty.hir_id);
399                             if let Some(def_id) = res.opt_def_id();
400                             if Some(def_id) == cx.tcx.lang_items().owned_box();
401                             // At this point, we know ty is Box<T>, now get T
402                             if let Some(ref last) = last_path_segment(ty_qpath).args;
403                             if let Some(boxed_ty) = last.args.iter().find_map(|arg| match arg {
404                                 GenericArg::Type(ty) => Some(ty),
405                                 _ => None,
406                             });
407                             let ty_ty = hir_ty_to_ty(cx.tcx, boxed_ty);
408                             if ty_ty.is_sized(cx.tcx.at(ty.span), cx.param_env);
409                             if let Ok(ty_ty_size) = cx.layout_of(ty_ty).map(|l| l.size.bytes());
410                             if ty_ty_size <= self.vec_box_size_threshold;
411                             then {
412                                 span_lint_and_sugg(
413                                     cx,
414                                     VEC_BOX,
415                                     hir_ty.span,
416                                     "`Vec<T>` is already on the heap, the boxing is unnecessary.",
417                                     "try",
418                                     format!("Vec<{}>", ty_ty),
419                                     Applicability::MachineApplicable,
420                                 );
421                                 return; // don't recurse into the type
422                             }
423                         }
424                     } else if match_def_path(cx, def_id, &paths::OPTION) {
425                         if match_type_parameter(cx, qpath, &paths::OPTION).is_some() {
426                             span_lint(
427                                 cx,
428                                 OPTION_OPTION,
429                                 hir_ty.span,
430                                 "consider using `Option<T>` instead of `Option<Option<T>>` or a custom \
431                                  enum if you need to distinguish all 3 cases",
432                             );
433                             return; // don't recurse into the type
434                         }
435                     } else if match_def_path(cx, def_id, &paths::LINKED_LIST) {
436                         span_lint_and_help(
437                             cx,
438                             LINKEDLIST,
439                             hir_ty.span,
440                             "I see you're using a LinkedList! Perhaps you meant some other data structure?",
441                             "a `VecDeque` might work",
442                         );
443                         return; // don't recurse into the type
444                     }
445                 }
446                 match *qpath {
447                     QPath::Resolved(Some(ref ty), ref p) => {
448                         self.check_ty(cx, ty, is_local);
449                         for ty in p.segments.iter().flat_map(|seg| {
450                             seg.args
451                                 .as_ref()
452                                 .map_or_else(|| [].iter(), |params| params.args.iter())
453                                 .filter_map(|arg| match arg {
454                                     GenericArg::Type(ty) => Some(ty),
455                                     _ => None,
456                                 })
457                         }) {
458                             self.check_ty(cx, ty, is_local);
459                         }
460                     },
461                     QPath::Resolved(None, ref p) => {
462                         for ty in p.segments.iter().flat_map(|seg| {
463                             seg.args
464                                 .as_ref()
465                                 .map_or_else(|| [].iter(), |params| params.args.iter())
466                                 .filter_map(|arg| match arg {
467                                     GenericArg::Type(ty) => Some(ty),
468                                     _ => None,
469                                 })
470                         }) {
471                             self.check_ty(cx, ty, is_local);
472                         }
473                     },
474                     QPath::TypeRelative(ref ty, ref seg) => {
475                         self.check_ty(cx, ty, is_local);
476                         if let Some(ref params) = seg.args {
477                             for ty in params.args.iter().filter_map(|arg| match arg {
478                                 GenericArg::Type(ty) => Some(ty),
479                                 _ => None,
480                             }) {
481                                 self.check_ty(cx, ty, is_local);
482                             }
483                         }
484                     },
485                 }
486             },
487             TyKind::Rptr(ref lt, ref mut_ty) => self.check_ty_rptr(cx, hir_ty, is_local, lt, mut_ty),
488             // recurse
489             TyKind::Slice(ref ty) | TyKind::Array(ref ty, _) | TyKind::Ptr(MutTy { ref ty, .. }) => {
490                 self.check_ty(cx, ty, is_local)
491             },
492             TyKind::Tup(tys) => {
493                 for ty in tys {
494                     self.check_ty(cx, ty, is_local);
495                 }
496             },
497             _ => {},
498         }
499     }
500
501     fn check_ty_rptr(
502         &mut self,
503         cx: &LateContext<'_, '_>,
504         hir_ty: &hir::Ty<'_>,
505         is_local: bool,
506         lt: &Lifetime,
507         mut_ty: &MutTy<'_>,
508     ) {
509         match mut_ty.ty.kind {
510             TyKind::Path(ref qpath) => {
511                 let hir_id = mut_ty.ty.hir_id;
512                 let def = qpath_res(cx, qpath, hir_id);
513                 if_chain! {
514                     if let Some(def_id) = def.opt_def_id();
515                     if Some(def_id) == cx.tcx.lang_items().owned_box();
516                     if let QPath::Resolved(None, ref path) = *qpath;
517                     if let [ref bx] = *path.segments;
518                     if let Some(ref params) = bx.args;
519                     if !params.parenthesized;
520                     if let Some(inner) = params.args.iter().find_map(|arg| match arg {
521                         GenericArg::Type(ty) => Some(ty),
522                         _ => None,
523                     });
524                     then {
525                         if is_any_trait(inner) {
526                             // Ignore `Box<Any>` types; see issue #1884 for details.
527                             return;
528                         }
529
530                         let ltopt = if lt.is_elided() {
531                             String::new()
532                         } else {
533                             format!("{} ", lt.name.ident().as_str())
534                         };
535                         let mutopt = if mut_ty.mutbl == Mutability::Mut {
536                             "mut "
537                         } else {
538                             ""
539                         };
540                         let mut applicability = Applicability::MachineApplicable;
541                         span_lint_and_sugg(
542                             cx,
543                             BORROWED_BOX,
544                             hir_ty.span,
545                             "you seem to be trying to use `&Box<T>`. Consider using just `&T`",
546                             "try",
547                             format!(
548                                 "&{}{}{}",
549                                 ltopt,
550                                 mutopt,
551                                 &snippet_with_applicability(cx, inner.span, "..", &mut applicability)
552                             ),
553                             Applicability::Unspecified,
554                         );
555                         return; // don't recurse into the type
556                     }
557                 };
558                 self.check_ty(cx, &mut_ty.ty, is_local);
559             },
560             _ => self.check_ty(cx, &mut_ty.ty, is_local),
561         }
562     }
563 }
564
565 // Returns true if given type is `Any` trait.
566 fn is_any_trait(t: &hir::Ty<'_>) -> bool {
567     if_chain! {
568         if let TyKind::TraitObject(ref traits, _) = t.kind;
569         if !traits.is_empty();
570         // Only Send/Sync can be used as additional traits, so it is enough to
571         // check only the first trait.
572         if match_path(&traits[0].trait_ref.path, &paths::ANY_TRAIT);
573         then {
574             return true;
575         }
576     }
577
578     false
579 }
580
581 declare_clippy_lint! {
582     /// **What it does:** Checks for binding a unit value.
583     ///
584     /// **Why is this bad?** A unit value cannot usefully be used anywhere. So
585     /// binding one is kind of pointless.
586     ///
587     /// **Known problems:** None.
588     ///
589     /// **Example:**
590     /// ```rust
591     /// let x = {
592     ///     1;
593     /// };
594     /// ```
595     pub LET_UNIT_VALUE,
596     style,
597     "creating a `let` binding to a value of unit type, which usually can't be used afterwards"
598 }
599
600 declare_lint_pass!(LetUnitValue => [LET_UNIT_VALUE]);
601
602 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for LetUnitValue {
603     fn check_stmt(&mut self, cx: &LateContext<'a, 'tcx>, stmt: &'tcx Stmt<'_>) {
604         if let StmtKind::Local(ref local) = stmt.kind {
605             if is_unit(cx.tables.pat_ty(&local.pat)) {
606                 if in_external_macro(cx.sess(), stmt.span) || local.pat.span.from_expansion() {
607                     return;
608                 }
609                 if higher::is_from_for_desugar(local) {
610                     return;
611                 }
612                 span_lint_and_then(cx, LET_UNIT_VALUE, stmt.span, "this let-binding has unit value", |db| {
613                     if let Some(expr) = &local.init {
614                         let snip = snippet_with_macro_callsite(cx, expr.span, "()");
615                         db.span_suggestion(
616                             stmt.span,
617                             "omit the `let` binding",
618                             format!("{};", snip),
619                             Applicability::MachineApplicable, // snippet
620                         );
621                     }
622                 });
623             }
624         }
625     }
626 }
627
628 declare_clippy_lint! {
629     /// **What it does:** Checks for comparisons to unit. This includes all binary
630     /// comparisons (like `==` and `<`) and asserts.
631     ///
632     /// **Why is this bad?** Unit is always equal to itself, and thus is just a
633     /// clumsily written constant. Mostly this happens when someone accidentally
634     /// adds semicolons at the end of the operands.
635     ///
636     /// **Known problems:** None.
637     ///
638     /// **Example:**
639     /// ```rust
640     /// # fn foo() {};
641     /// # fn bar() {};
642     /// # fn baz() {};
643     /// if {
644     ///     foo();
645     /// } == {
646     ///     bar();
647     /// } {
648     ///     baz();
649     /// }
650     /// ```
651     /// is equal to
652     /// ```rust
653     /// # fn foo() {};
654     /// # fn bar() {};
655     /// # fn baz() {};
656     /// {
657     ///     foo();
658     ///     bar();
659     ///     baz();
660     /// }
661     /// ```
662     ///
663     /// For asserts:
664     /// ```rust
665     /// # fn foo() {};
666     /// # fn bar() {};
667     /// assert_eq!({ foo(); }, { bar(); });
668     /// ```
669     /// will always succeed
670     pub UNIT_CMP,
671     correctness,
672     "comparing unit values"
673 }
674
675 declare_lint_pass!(UnitCmp => [UNIT_CMP]);
676
677 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitCmp {
678     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) {
679         if expr.span.from_expansion() {
680             if let Some(callee) = expr.span.source_callee() {
681                 if let ExpnKind::Macro(MacroKind::Bang, symbol) = callee.kind {
682                     if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
683                         let op = cmp.node;
684                         if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
685                             let result = match &*symbol.as_str() {
686                                 "assert_eq" | "debug_assert_eq" => "succeed",
687                                 "assert_ne" | "debug_assert_ne" => "fail",
688                                 _ => return,
689                             };
690                             span_lint(
691                                 cx,
692                                 UNIT_CMP,
693                                 expr.span,
694                                 &format!(
695                                     "`{}` of unit values detected. This will always {}",
696                                     symbol.as_str(),
697                                     result
698                                 ),
699                             );
700                         }
701                     }
702                 }
703             }
704             return;
705         }
706         if let ExprKind::Binary(ref cmp, ref left, _) = expr.kind {
707             let op = cmp.node;
708             if op.is_comparison() && is_unit(cx.tables.expr_ty(left)) {
709                 let result = match op {
710                     BinOpKind::Eq | BinOpKind::Le | BinOpKind::Ge => "true",
711                     _ => "false",
712                 };
713                 span_lint(
714                     cx,
715                     UNIT_CMP,
716                     expr.span,
717                     &format!(
718                         "{}-comparison of unit values detected. This will always be {}",
719                         op.as_str(),
720                         result
721                     ),
722                 );
723             }
724         }
725     }
726 }
727
728 declare_clippy_lint! {
729     /// **What it does:** Checks for passing a unit value as an argument to a function without using a
730     /// unit literal (`()`).
731     ///
732     /// **Why is this bad?** This is likely the result of an accidental semicolon.
733     ///
734     /// **Known problems:** None.
735     ///
736     /// **Example:**
737     /// ```rust,ignore
738     /// foo({
739     ///     let a = bar();
740     ///     baz(a);
741     /// })
742     /// ```
743     pub UNIT_ARG,
744     complexity,
745     "passing unit to a function"
746 }
747
748 declare_lint_pass!(UnitArg => [UNIT_ARG]);
749
750 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnitArg {
751     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
752         if expr.span.from_expansion() {
753             return;
754         }
755
756         // apparently stuff in the desugaring of `?` can trigger this
757         // so check for that here
758         // only the calls to `Try::from_error` is marked as desugared,
759         // so we need to check both the current Expr and its parent.
760         if is_questionmark_desugar_marked_call(expr) {
761             return;
762         }
763         if_chain! {
764             let map = &cx.tcx.hir();
765             let opt_parent_node = map.find(map.get_parent_node(expr.hir_id));
766             if let Some(hir::Node::Expr(parent_expr)) = opt_parent_node;
767             if is_questionmark_desugar_marked_call(parent_expr);
768             then {
769                 return;
770             }
771         }
772
773         match expr.kind {
774             ExprKind::Call(_, args) | ExprKind::MethodCall(_, _, args) => {
775                 for arg in args {
776                     if is_unit(cx.tables.expr_ty(arg)) && !is_unit_literal(arg) {
777                         if let ExprKind::Match(.., match_source) = &arg.kind {
778                             if *match_source == MatchSource::TryDesugar {
779                                 continue;
780                             }
781                         }
782
783                         span_lint_and_sugg(
784                             cx,
785                             UNIT_ARG,
786                             arg.span,
787                             "passing a unit value to a function",
788                             "if you intended to pass a unit value, use a unit literal instead",
789                             "()".to_string(),
790                             Applicability::MachineApplicable,
791                         );
792                     }
793                 }
794             },
795             _ => (),
796         }
797     }
798 }
799
800 fn is_questionmark_desugar_marked_call(expr: &Expr<'_>) -> bool {
801     use rustc_span::hygiene::DesugaringKind;
802     if let ExprKind::Call(ref callee, _) = expr.kind {
803         callee.span.is_desugaring(DesugaringKind::QuestionMark)
804     } else {
805         false
806     }
807 }
808
809 fn is_unit(ty: Ty<'_>) -> bool {
810     match ty.kind {
811         ty::Tuple(slice) if slice.is_empty() => true,
812         _ => false,
813     }
814 }
815
816 fn is_unit_literal(expr: &Expr<'_>) -> bool {
817     match expr.kind {
818         ExprKind::Tup(ref slice) if slice.is_empty() => true,
819         _ => false,
820     }
821 }
822
823 declare_clippy_lint! {
824     /// **What it does:** Checks for casts from any numerical to a float type where
825     /// the receiving type cannot store all values from the original type without
826     /// rounding errors. This possible rounding is to be expected, so this lint is
827     /// `Allow` by default.
828     ///
829     /// Basically, this warns on casting any integer with 32 or more bits to `f32`
830     /// or any 64-bit integer to `f64`.
831     ///
832     /// **Why is this bad?** It's not bad at all. But in some applications it can be
833     /// helpful to know where precision loss can take place. This lint can help find
834     /// those places in the code.
835     ///
836     /// **Known problems:** None.
837     ///
838     /// **Example:**
839     /// ```rust
840     /// let x = std::u64::MAX;
841     /// x as f64;
842     /// ```
843     pub CAST_PRECISION_LOSS,
844     pedantic,
845     "casts that cause loss of precision, e.g., `x as f32` where `x: u64`"
846 }
847
848 declare_clippy_lint! {
849     /// **What it does:** Checks for casts from a signed to an unsigned numerical
850     /// type. In this case, negative values wrap around to large positive values,
851     /// which can be quite surprising in practice. However, as the cast works as
852     /// defined, this lint is `Allow` by default.
853     ///
854     /// **Why is this bad?** Possibly surprising results. You can activate this lint
855     /// as a one-time check to see where numerical wrapping can arise.
856     ///
857     /// **Known problems:** None.
858     ///
859     /// **Example:**
860     /// ```rust
861     /// let y: i8 = -1;
862     /// y as u128; // will return 18446744073709551615
863     /// ```
864     pub CAST_SIGN_LOSS,
865     pedantic,
866     "casts from signed types to unsigned types, e.g., `x as u32` where `x: i32`"
867 }
868
869 declare_clippy_lint! {
870     /// **What it does:** Checks for casts between numerical types that may
871     /// truncate large values. This is expected behavior, so the cast is `Allow` by
872     /// default.
873     ///
874     /// **Why is this bad?** In some problem domains, it is good practice to avoid
875     /// truncation. This lint can be activated to help assess where additional
876     /// checks could be beneficial.
877     ///
878     /// **Known problems:** None.
879     ///
880     /// **Example:**
881     /// ```rust
882     /// fn as_u8(x: u64) -> u8 {
883     ///     x as u8
884     /// }
885     /// ```
886     pub CAST_POSSIBLE_TRUNCATION,
887     pedantic,
888     "casts that may cause truncation of the value, e.g., `x as u8` where `x: u32`, or `x as i32` where `x: f32`"
889 }
890
891 declare_clippy_lint! {
892     /// **What it does:** Checks for casts from an unsigned type to a signed type of
893     /// the same size. Performing such a cast is a 'no-op' for the compiler,
894     /// i.e., nothing is changed at the bit level, and the binary representation of
895     /// the value is reinterpreted. This can cause wrapping if the value is too big
896     /// for the target signed type. However, the cast works as defined, so this lint
897     /// is `Allow` by default.
898     ///
899     /// **Why is this bad?** While such a cast is not bad in itself, the results can
900     /// be surprising when this is not the intended behavior, as demonstrated by the
901     /// example below.
902     ///
903     /// **Known problems:** None.
904     ///
905     /// **Example:**
906     /// ```rust
907     /// std::u32::MAX as i32; // will yield a value of `-1`
908     /// ```
909     pub CAST_POSSIBLE_WRAP,
910     pedantic,
911     "casts that may cause wrapping around the value, e.g., `x as i32` where `x: u32` and `x > i32::MAX`"
912 }
913
914 declare_clippy_lint! {
915     /// **What it does:** Checks for casts between numerical types that may
916     /// be replaced by safe conversion functions.
917     ///
918     /// **Why is this bad?** Rust's `as` keyword will perform many kinds of
919     /// conversions, including silently lossy conversions. Conversion functions such
920     /// as `i32::from` will only perform lossless conversions. Using the conversion
921     /// functions prevents conversions from turning into silent lossy conversions if
922     /// the types of the input expressions ever change, and make it easier for
923     /// people reading the code to know that the conversion is lossless.
924     ///
925     /// **Known problems:** None.
926     ///
927     /// **Example:**
928     /// ```rust
929     /// fn as_u64(x: u8) -> u64 {
930     ///     x as u64
931     /// }
932     /// ```
933     ///
934     /// Using `::from` would look like this:
935     ///
936     /// ```rust
937     /// fn as_u64(x: u8) -> u64 {
938     ///     u64::from(x)
939     /// }
940     /// ```
941     pub CAST_LOSSLESS,
942     pedantic,
943     "casts using `as` that are known to be lossless, e.g., `x as u64` where `x: u8`"
944 }
945
946 declare_clippy_lint! {
947     /// **What it does:** Checks for casts to the same type.
948     ///
949     /// **Why is this bad?** It's just unnecessary.
950     ///
951     /// **Known problems:** None.
952     ///
953     /// **Example:**
954     /// ```rust
955     /// let _ = 2i32 as i32;
956     /// ```
957     pub UNNECESSARY_CAST,
958     complexity,
959     "cast to the same type, e.g., `x as i32` where `x: i32`"
960 }
961
962 declare_clippy_lint! {
963     /// **What it does:** Checks for casts from a less-strictly-aligned pointer to a
964     /// more-strictly-aligned pointer
965     ///
966     /// **Why is this bad?** Dereferencing the resulting pointer may be undefined
967     /// behavior.
968     ///
969     /// **Known problems:** Using `std::ptr::read_unaligned` and `std::ptr::write_unaligned` or similar
970     /// on the resulting pointer is fine.
971     ///
972     /// **Example:**
973     /// ```rust
974     /// let _ = (&1u8 as *const u8) as *const u16;
975     /// let _ = (&mut 1u8 as *mut u8) as *mut u16;
976     /// ```
977     pub CAST_PTR_ALIGNMENT,
978     correctness,
979     "cast from a pointer to a more-strictly-aligned pointer"
980 }
981
982 declare_clippy_lint! {
983     /// **What it does:** Checks for casts of function pointers to something other than usize
984     ///
985     /// **Why is this bad?**
986     /// Casting a function pointer to anything other than usize/isize is not portable across
987     /// architectures, because you end up losing bits if the target type is too small or end up with a
988     /// bunch of extra bits that waste space and add more instructions to the final binary than
989     /// strictly necessary for the problem
990     ///
991     /// Casting to isize also doesn't make sense since there are no signed addresses.
992     ///
993     /// **Example**
994     ///
995     /// ```rust
996     /// // Bad
997     /// fn fun() -> i32 { 1 }
998     /// let a = fun as i64;
999     ///
1000     /// // Good
1001     /// fn fun2() -> i32 { 1 }
1002     /// let a = fun2 as usize;
1003     /// ```
1004     pub FN_TO_NUMERIC_CAST,
1005     style,
1006     "casting a function pointer to a numeric type other than usize"
1007 }
1008
1009 declare_clippy_lint! {
1010     /// **What it does:** Checks for casts of a function pointer to a numeric type not wide enough to
1011     /// store address.
1012     ///
1013     /// **Why is this bad?**
1014     /// Such a cast discards some bits of the function's address. If this is intended, it would be more
1015     /// clearly expressed by casting to usize first, then casting the usize to the intended type (with
1016     /// a comment) to perform the truncation.
1017     ///
1018     /// **Example**
1019     ///
1020     /// ```rust
1021     /// // Bad
1022     /// fn fn1() -> i16 {
1023     ///     1
1024     /// };
1025     /// let _ = fn1 as i32;
1026     ///
1027     /// // Better: Cast to usize first, then comment with the reason for the truncation
1028     /// fn fn2() -> i16 {
1029     ///     1
1030     /// };
1031     /// let fn_ptr = fn2 as usize;
1032     /// let fn_ptr_truncated = fn_ptr as i32;
1033     /// ```
1034     pub FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1035     style,
1036     "casting a function pointer to a numeric type not wide enough to store the address"
1037 }
1038
1039 /// Returns the size in bits of an integral type.
1040 /// Will return 0 if the type is not an int or uint variant
1041 fn int_ty_to_nbits(typ: Ty<'_>, tcx: TyCtxt<'_>) -> u64 {
1042     match typ.kind {
1043         ty::Int(i) => match i {
1044             IntTy::Isize => tcx.data_layout.pointer_size.bits(),
1045             IntTy::I8 => 8,
1046             IntTy::I16 => 16,
1047             IntTy::I32 => 32,
1048             IntTy::I64 => 64,
1049             IntTy::I128 => 128,
1050         },
1051         ty::Uint(i) => match i {
1052             UintTy::Usize => tcx.data_layout.pointer_size.bits(),
1053             UintTy::U8 => 8,
1054             UintTy::U16 => 16,
1055             UintTy::U32 => 32,
1056             UintTy::U64 => 64,
1057             UintTy::U128 => 128,
1058         },
1059         _ => 0,
1060     }
1061 }
1062
1063 fn is_isize_or_usize(typ: Ty<'_>) -> bool {
1064     match typ.kind {
1065         ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => true,
1066         _ => false,
1067     }
1068 }
1069
1070 fn span_precision_loss_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to_f64: bool) {
1071     let mantissa_nbits = if cast_to_f64 { 52 } else { 23 };
1072     let arch_dependent = is_isize_or_usize(cast_from) && cast_to_f64;
1073     let arch_dependent_str = "on targets with 64-bit wide pointers ";
1074     let from_nbits_str = if arch_dependent {
1075         "64".to_owned()
1076     } else if is_isize_or_usize(cast_from) {
1077         "32 or 64".to_owned()
1078     } else {
1079         int_ty_to_nbits(cast_from, cx.tcx).to_string()
1080     };
1081     span_lint(
1082         cx,
1083         CAST_PRECISION_LOSS,
1084         expr.span,
1085         &format!(
1086             "casting `{0}` to `{1}` causes a loss of precision {2}(`{0}` is {3} bits wide, \
1087              but `{1}`'s mantissa is only {4} bits wide)",
1088             cast_from,
1089             if cast_to_f64 { "f64" } else { "f32" },
1090             if arch_dependent { arch_dependent_str } else { "" },
1091             from_nbits_str,
1092             mantissa_nbits
1093         ),
1094     );
1095 }
1096
1097 fn should_strip_parens(op: &Expr<'_>, snip: &str) -> bool {
1098     if let ExprKind::Binary(_, _, _) = op.kind {
1099         if snip.starts_with('(') && snip.ends_with(')') {
1100             return true;
1101         }
1102     }
1103     false
1104 }
1105
1106 fn span_lossless_lint(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1107     // Do not suggest using From in consts/statics until it is valid to do so (see #2267).
1108     if in_constant(cx, expr.hir_id) {
1109         return;
1110     }
1111     // The suggestion is to use a function call, so if the original expression
1112     // has parens on the outside, they are no longer needed.
1113     let mut applicability = Applicability::MachineApplicable;
1114     let opt = snippet_opt(cx, op.span);
1115     let sugg = if let Some(ref snip) = opt {
1116         if should_strip_parens(op, snip) {
1117             &snip[1..snip.len() - 1]
1118         } else {
1119             snip.as_str()
1120         }
1121     } else {
1122         applicability = Applicability::HasPlaceholders;
1123         ".."
1124     };
1125
1126     span_lint_and_sugg(
1127         cx,
1128         CAST_LOSSLESS,
1129         expr.span,
1130         &format!(
1131             "casting `{}` to `{}` may become silently lossy if you later change the type",
1132             cast_from, cast_to
1133         ),
1134         "try",
1135         format!("{}::from({})", cast_to, sugg),
1136         applicability,
1137     );
1138 }
1139
1140 enum ArchSuffix {
1141     _32,
1142     _64,
1143     None,
1144 }
1145
1146 fn check_loss_of_sign(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1147     if !cast_from.is_signed() || cast_to.is_signed() {
1148         return;
1149     }
1150
1151     // don't lint for positive constants
1152     let const_val = constant(cx, &cx.tables, op);
1153     if_chain! {
1154         if let Some((const_val, _)) = const_val;
1155         if let Constant::Int(n) = const_val;
1156         if let ty::Int(ity) = cast_from.kind;
1157         if sext(cx.tcx, n, ity) >= 0;
1158         then {
1159             return
1160         }
1161     }
1162
1163     // don't lint for the result of methods that always return non-negative values
1164     if let ExprKind::MethodCall(ref path, _, _) = op.kind {
1165         let mut method_name = path.ident.name.as_str();
1166         let whitelisted_methods = ["abs", "checked_abs", "rem_euclid", "checked_rem_euclid"];
1167
1168         if_chain! {
1169             if method_name == "unwrap";
1170             if let Some(arglist) = method_chain_args(op, &["unwrap"]);
1171             if let ExprKind::MethodCall(ref inner_path, _, _) = &arglist[0][0].kind;
1172             then {
1173                 method_name = inner_path.ident.name.as_str();
1174             }
1175         }
1176
1177         if whitelisted_methods.iter().any(|&name| method_name == name) {
1178             return;
1179         }
1180     }
1181
1182     span_lint(
1183         cx,
1184         CAST_SIGN_LOSS,
1185         expr.span,
1186         &format!(
1187             "casting `{}` to `{}` may lose the sign of the value",
1188             cast_from, cast_to
1189         ),
1190     );
1191 }
1192
1193 fn check_truncation_and_wrapping(cx: &LateContext<'_, '_>, expr: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1194     let arch_64_suffix = " on targets with 64-bit wide pointers";
1195     let arch_32_suffix = " on targets with 32-bit wide pointers";
1196     let cast_unsigned_to_signed = !cast_from.is_signed() && cast_to.is_signed();
1197     let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1198     let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1199     let (span_truncation, suffix_truncation, span_wrap, suffix_wrap) =
1200         match (is_isize_or_usize(cast_from), is_isize_or_usize(cast_to)) {
1201             (true, true) | (false, false) => (
1202                 to_nbits < from_nbits,
1203                 ArchSuffix::None,
1204                 to_nbits == from_nbits && cast_unsigned_to_signed,
1205                 ArchSuffix::None,
1206             ),
1207             (true, false) => (
1208                 to_nbits <= 32,
1209                 if to_nbits == 32 {
1210                     ArchSuffix::_64
1211                 } else {
1212                     ArchSuffix::None
1213                 },
1214                 to_nbits <= 32 && cast_unsigned_to_signed,
1215                 ArchSuffix::_32,
1216             ),
1217             (false, true) => (
1218                 from_nbits == 64,
1219                 ArchSuffix::_32,
1220                 cast_unsigned_to_signed,
1221                 if from_nbits == 64 {
1222                     ArchSuffix::_64
1223                 } else {
1224                     ArchSuffix::_32
1225                 },
1226             ),
1227         };
1228     if span_truncation {
1229         span_lint(
1230             cx,
1231             CAST_POSSIBLE_TRUNCATION,
1232             expr.span,
1233             &format!(
1234                 "casting `{}` to `{}` may truncate the value{}",
1235                 cast_from,
1236                 cast_to,
1237                 match suffix_truncation {
1238                     ArchSuffix::_32 => arch_32_suffix,
1239                     ArchSuffix::_64 => arch_64_suffix,
1240                     ArchSuffix::None => "",
1241                 }
1242             ),
1243         );
1244     }
1245     if span_wrap {
1246         span_lint(
1247             cx,
1248             CAST_POSSIBLE_WRAP,
1249             expr.span,
1250             &format!(
1251                 "casting `{}` to `{}` may wrap around the value{}",
1252                 cast_from,
1253                 cast_to,
1254                 match suffix_wrap {
1255                     ArchSuffix::_32 => arch_32_suffix,
1256                     ArchSuffix::_64 => arch_64_suffix,
1257                     ArchSuffix::None => "",
1258                 }
1259             ),
1260         );
1261     }
1262 }
1263
1264 fn check_lossless(cx: &LateContext<'_, '_>, expr: &Expr<'_>, op: &Expr<'_>, cast_from: Ty<'_>, cast_to: Ty<'_>) {
1265     let cast_signed_to_unsigned = cast_from.is_signed() && !cast_to.is_signed();
1266     let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1267     let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1268     if !is_isize_or_usize(cast_from) && !is_isize_or_usize(cast_to) && from_nbits < to_nbits && !cast_signed_to_unsigned
1269     {
1270         span_lossless_lint(cx, expr, op, cast_from, cast_to);
1271     }
1272 }
1273
1274 declare_lint_pass!(Casts => [
1275     CAST_PRECISION_LOSS,
1276     CAST_SIGN_LOSS,
1277     CAST_POSSIBLE_TRUNCATION,
1278     CAST_POSSIBLE_WRAP,
1279     CAST_LOSSLESS,
1280     UNNECESSARY_CAST,
1281     CAST_PTR_ALIGNMENT,
1282     FN_TO_NUMERIC_CAST,
1283     FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1284 ]);
1285
1286 // Check if the given type is either `core::ffi::c_void` or
1287 // one of the platform specific `libc::<platform>::c_void` of libc.
1288 fn is_c_void(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
1289     if let ty::Adt(adt, _) = ty.kind {
1290         let names = cx.get_def_path(adt.did);
1291
1292         if names.is_empty() {
1293             return false;
1294         }
1295         if names[0] == sym!(libc) || names[0] == sym::core && *names.last().unwrap() == sym!(c_void) {
1296             return true;
1297         }
1298     }
1299     false
1300 }
1301
1302 /// Returns the mantissa bits wide of a fp type.
1303 /// Will return 0 if the type is not a fp
1304 fn fp_ty_mantissa_nbits(typ: Ty<'_>) -> u32 {
1305     match typ.kind {
1306         ty::Float(FloatTy::F32) => 23,
1307         ty::Float(FloatTy::F64) | ty::Infer(InferTy::FloatVar(_)) => 52,
1308         _ => 0,
1309     }
1310 }
1311
1312 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Casts {
1313     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1314         if expr.span.from_expansion() {
1315             return;
1316         }
1317         if let ExprKind::Cast(ref ex, _) = expr.kind {
1318             let (cast_from, cast_to) = (cx.tables.expr_ty(ex), cx.tables.expr_ty(expr));
1319             lint_fn_to_numeric_cast(cx, expr, ex, cast_from, cast_to);
1320             if let ExprKind::Lit(ref lit) = ex.kind {
1321                 if_chain! {
1322                     if let LitKind::Int(n, _) = lit.node;
1323                     if let Some(src) = snippet_opt(cx, lit.span);
1324                     if cast_to.is_floating_point();
1325                     if let Some(num_lit) = NumericLiteral::from_lit_kind(&src, &lit.node);
1326                     let from_nbits = 128 - n.leading_zeros();
1327                     let to_nbits = fp_ty_mantissa_nbits(cast_to);
1328                     if from_nbits != 0 && to_nbits != 0 && from_nbits <= to_nbits && num_lit.is_decimal();
1329                     then {
1330                         span_lint_and_sugg(
1331                             cx,
1332                             UNNECESSARY_CAST,
1333                             expr.span,
1334                             &format!("casting integer literal to `{}` is unnecessary", cast_to),
1335                             "try",
1336                             format!("{}_{}", n, cast_to),
1337                             Applicability::MachineApplicable,
1338                         );
1339                         return;
1340                     }
1341                 }
1342                 match lit.node {
1343                     LitKind::Int(_, LitIntType::Unsuffixed) | LitKind::Float(_, LitFloatType::Unsuffixed) => {},
1344                     _ => {
1345                         if cast_from.kind == cast_to.kind && !in_external_macro(cx.sess(), expr.span) {
1346                             span_lint(
1347                                 cx,
1348                                 UNNECESSARY_CAST,
1349                                 expr.span,
1350                                 &format!(
1351                                     "casting to the same type is unnecessary (`{}` -> `{}`)",
1352                                     cast_from, cast_to
1353                                 ),
1354                             );
1355                         }
1356                     },
1357                 }
1358             }
1359             if cast_from.is_numeric() && cast_to.is_numeric() && !in_external_macro(cx.sess(), expr.span) {
1360                 lint_numeric_casts(cx, expr, ex, cast_from, cast_to);
1361             }
1362
1363             lint_cast_ptr_alignment(cx, expr, cast_from, cast_to);
1364         }
1365     }
1366 }
1367
1368 fn lint_numeric_casts<'tcx>(
1369     cx: &LateContext<'_, 'tcx>,
1370     expr: &Expr<'tcx>,
1371     cast_expr: &Expr<'_>,
1372     cast_from: Ty<'tcx>,
1373     cast_to: Ty<'tcx>,
1374 ) {
1375     match (cast_from.is_integral(), cast_to.is_integral()) {
1376         (true, false) => {
1377             let from_nbits = int_ty_to_nbits(cast_from, cx.tcx);
1378             let to_nbits = if let ty::Float(FloatTy::F32) = cast_to.kind {
1379                 32
1380             } else {
1381                 64
1382             };
1383             if is_isize_or_usize(cast_from) || from_nbits >= to_nbits {
1384                 span_precision_loss_lint(cx, expr, cast_from, to_nbits == 64);
1385             }
1386             if from_nbits < to_nbits {
1387                 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1388             }
1389         },
1390         (false, true) => {
1391             span_lint(
1392                 cx,
1393                 CAST_POSSIBLE_TRUNCATION,
1394                 expr.span,
1395                 &format!("casting `{}` to `{}` may truncate the value", cast_from, cast_to),
1396             );
1397             if !cast_to.is_signed() {
1398                 span_lint(
1399                     cx,
1400                     CAST_SIGN_LOSS,
1401                     expr.span,
1402                     &format!(
1403                         "casting `{}` to `{}` may lose the sign of the value",
1404                         cast_from, cast_to
1405                     ),
1406                 );
1407             }
1408         },
1409         (true, true) => {
1410             check_loss_of_sign(cx, expr, cast_expr, cast_from, cast_to);
1411             check_truncation_and_wrapping(cx, expr, cast_from, cast_to);
1412             check_lossless(cx, expr, cast_expr, cast_from, cast_to);
1413         },
1414         (false, false) => {
1415             if let (&ty::Float(FloatTy::F64), &ty::Float(FloatTy::F32)) = (&cast_from.kind, &cast_to.kind) {
1416                 span_lint(
1417                     cx,
1418                     CAST_POSSIBLE_TRUNCATION,
1419                     expr.span,
1420                     "casting `f64` to `f32` may truncate the value",
1421                 );
1422             }
1423             if let (&ty::Float(FloatTy::F32), &ty::Float(FloatTy::F64)) = (&cast_from.kind, &cast_to.kind) {
1424                 span_lossless_lint(cx, expr, cast_expr, cast_from, cast_to);
1425             }
1426         },
1427     }
1428 }
1429
1430 fn lint_cast_ptr_alignment<'tcx>(cx: &LateContext<'_, 'tcx>, expr: &Expr<'_>, cast_from: Ty<'tcx>, cast_to: Ty<'tcx>) {
1431     if_chain! {
1432         if let ty::RawPtr(from_ptr_ty) = &cast_from.kind;
1433         if let ty::RawPtr(to_ptr_ty) = &cast_to.kind;
1434         if let Ok(from_layout) = cx.layout_of(from_ptr_ty.ty);
1435         if let Ok(to_layout) = cx.layout_of(to_ptr_ty.ty);
1436         if from_layout.align.abi < to_layout.align.abi;
1437         // with c_void, we inherently need to trust the user
1438         if !is_c_void(cx, from_ptr_ty.ty);
1439         // when casting from a ZST, we don't know enough to properly lint
1440         if !from_layout.is_zst();
1441         then {
1442             span_lint(
1443                 cx,
1444                 CAST_PTR_ALIGNMENT,
1445                 expr.span,
1446                 &format!(
1447                     "casting from `{}` to a more-strictly-aligned pointer (`{}`) ({} < {} bytes)",
1448                     cast_from,
1449                     cast_to,
1450                     from_layout.align.abi.bytes(),
1451                     to_layout.align.abi.bytes(),
1452                 ),
1453             );
1454         }
1455     }
1456 }
1457
1458 fn lint_fn_to_numeric_cast(
1459     cx: &LateContext<'_, '_>,
1460     expr: &Expr<'_>,
1461     cast_expr: &Expr<'_>,
1462     cast_from: Ty<'_>,
1463     cast_to: Ty<'_>,
1464 ) {
1465     // We only want to check casts to `ty::Uint` or `ty::Int`
1466     match cast_to.kind {
1467         ty::Uint(_) | ty::Int(..) => { /* continue on */ },
1468         _ => return,
1469     }
1470     match cast_from.kind {
1471         ty::FnDef(..) | ty::FnPtr(_) => {
1472             let mut applicability = Applicability::MaybeIncorrect;
1473             let from_snippet = snippet_with_applicability(cx, cast_expr.span, "x", &mut applicability);
1474
1475             let to_nbits = int_ty_to_nbits(cast_to, cx.tcx);
1476             if to_nbits < cx.tcx.data_layout.pointer_size.bits() {
1477                 span_lint_and_sugg(
1478                     cx,
1479                     FN_TO_NUMERIC_CAST_WITH_TRUNCATION,
1480                     expr.span,
1481                     &format!(
1482                         "casting function pointer `{}` to `{}`, which truncates the value",
1483                         from_snippet, cast_to
1484                     ),
1485                     "try",
1486                     format!("{} as usize", from_snippet),
1487                     applicability,
1488                 );
1489             } else if cast_to.kind != ty::Uint(UintTy::Usize) {
1490                 span_lint_and_sugg(
1491                     cx,
1492                     FN_TO_NUMERIC_CAST,
1493                     expr.span,
1494                     &format!("casting function pointer `{}` to `{}`", from_snippet, cast_to),
1495                     "try",
1496                     format!("{} as usize", from_snippet),
1497                     applicability,
1498                 );
1499             }
1500         },
1501         _ => {},
1502     }
1503 }
1504
1505 declare_clippy_lint! {
1506     /// **What it does:** Checks for types used in structs, parameters and `let`
1507     /// declarations above a certain complexity threshold.
1508     ///
1509     /// **Why is this bad?** Too complex types make the code less readable. Consider
1510     /// using a `type` definition to simplify them.
1511     ///
1512     /// **Known problems:** None.
1513     ///
1514     /// **Example:**
1515     /// ```rust
1516     /// # use std::rc::Rc;
1517     /// struct Foo {
1518     ///     inner: Rc<Vec<Vec<Box<(u32, u32, u32, u32)>>>>,
1519     /// }
1520     /// ```
1521     pub TYPE_COMPLEXITY,
1522     complexity,
1523     "usage of very complex types that might be better factored into `type` definitions"
1524 }
1525
1526 pub struct TypeComplexity {
1527     threshold: u64,
1528 }
1529
1530 impl TypeComplexity {
1531     #[must_use]
1532     pub fn new(threshold: u64) -> Self {
1533         Self { threshold }
1534     }
1535 }
1536
1537 impl_lint_pass!(TypeComplexity => [TYPE_COMPLEXITY]);
1538
1539 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for TypeComplexity {
1540     fn check_fn(
1541         &mut self,
1542         cx: &LateContext<'a, 'tcx>,
1543         _: FnKind<'tcx>,
1544         decl: &'tcx FnDecl<'_>,
1545         _: &'tcx Body<'_>,
1546         _: Span,
1547         _: HirId,
1548     ) {
1549         self.check_fndecl(cx, decl);
1550     }
1551
1552     fn check_struct_field(&mut self, cx: &LateContext<'a, 'tcx>, field: &'tcx hir::StructField<'_>) {
1553         // enum variants are also struct fields now
1554         self.check_type(cx, &field.ty);
1555     }
1556
1557     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
1558         match item.kind {
1559             ItemKind::Static(ref ty, _, _) | ItemKind::Const(ref ty, _) => self.check_type(cx, ty),
1560             // functions, enums, structs, impls and traits are covered
1561             _ => (),
1562         }
1563     }
1564
1565     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
1566         match item.kind {
1567             TraitItemKind::Const(ref ty, _) | TraitItemKind::Type(_, Some(ref ty)) => self.check_type(cx, ty),
1568             TraitItemKind::Fn(FnSig { ref decl, .. }, TraitFn::Required(_)) => self.check_fndecl(cx, decl),
1569             // methods with default impl are covered by check_fn
1570             _ => (),
1571         }
1572     }
1573
1574     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
1575         match item.kind {
1576             ImplItemKind::Const(ref ty, _) | ImplItemKind::TyAlias(ref ty) => self.check_type(cx, ty),
1577             // methods are covered by check_fn
1578             _ => (),
1579         }
1580     }
1581
1582     fn check_local(&mut self, cx: &LateContext<'a, 'tcx>, local: &'tcx Local<'_>) {
1583         if let Some(ref ty) = local.ty {
1584             self.check_type(cx, ty);
1585         }
1586     }
1587 }
1588
1589 impl<'a, 'tcx> TypeComplexity {
1590     fn check_fndecl(&self, cx: &LateContext<'a, 'tcx>, decl: &'tcx FnDecl<'_>) {
1591         for arg in decl.inputs {
1592             self.check_type(cx, arg);
1593         }
1594         if let FnRetTy::Return(ref ty) = decl.output {
1595             self.check_type(cx, ty);
1596         }
1597     }
1598
1599     fn check_type(&self, cx: &LateContext<'_, '_>, ty: &hir::Ty<'_>) {
1600         if ty.span.from_expansion() {
1601             return;
1602         }
1603         let score = {
1604             let mut visitor = TypeComplexityVisitor { score: 0, nest: 1 };
1605             visitor.visit_ty(ty);
1606             visitor.score
1607         };
1608
1609         if score > self.threshold {
1610             span_lint(
1611                 cx,
1612                 TYPE_COMPLEXITY,
1613                 ty.span,
1614                 "very complex type used. Consider factoring parts into `type` definitions",
1615             );
1616         }
1617     }
1618 }
1619
1620 /// Walks a type and assigns a complexity score to it.
1621 struct TypeComplexityVisitor {
1622     /// total complexity score of the type
1623     score: u64,
1624     /// current nesting level
1625     nest: u64,
1626 }
1627
1628 impl<'tcx> Visitor<'tcx> for TypeComplexityVisitor {
1629     type Map = Map<'tcx>;
1630
1631     fn visit_ty(&mut self, ty: &'tcx hir::Ty<'_>) {
1632         let (add_score, sub_nest) = match ty.kind {
1633             // _, &x and *x have only small overhead; don't mess with nesting level
1634             TyKind::Infer | TyKind::Ptr(..) | TyKind::Rptr(..) => (1, 0),
1635
1636             // the "normal" components of a type: named types, arrays/tuples
1637             TyKind::Path(..) | TyKind::Slice(..) | TyKind::Tup(..) | TyKind::Array(..) => (10 * self.nest, 1),
1638
1639             // function types bring a lot of overhead
1640             TyKind::BareFn(ref bare) if bare.abi == Abi::Rust => (50 * self.nest, 1),
1641
1642             TyKind::TraitObject(ref param_bounds, _) => {
1643                 let has_lifetime_parameters = param_bounds.iter().any(|bound| {
1644                     bound.bound_generic_params.iter().any(|gen| match gen.kind {
1645                         GenericParamKind::Lifetime { .. } => true,
1646                         _ => false,
1647                     })
1648                 });
1649                 if has_lifetime_parameters {
1650                     // complex trait bounds like A<'a, 'b>
1651                     (50 * self.nest, 1)
1652                 } else {
1653                     // simple trait bounds like A + B
1654                     (20 * self.nest, 0)
1655                 }
1656             },
1657
1658             _ => (0, 0),
1659         };
1660         self.score += add_score;
1661         self.nest += sub_nest;
1662         walk_ty(self, ty);
1663         self.nest -= sub_nest;
1664     }
1665     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
1666         NestedVisitorMap::None
1667     }
1668 }
1669
1670 declare_clippy_lint! {
1671     /// **What it does:** Checks for expressions where a character literal is cast
1672     /// to `u8` and suggests using a byte literal instead.
1673     ///
1674     /// **Why is this bad?** In general, casting values to smaller types is
1675     /// error-prone and should be avoided where possible. In the particular case of
1676     /// converting a character literal to u8, it is easy to avoid by just using a
1677     /// byte literal instead. As an added bonus, `b'a'` is even slightly shorter
1678     /// than `'a' as u8`.
1679     ///
1680     /// **Known problems:** None.
1681     ///
1682     /// **Example:**
1683     /// ```rust,ignore
1684     /// 'x' as u8
1685     /// ```
1686     ///
1687     /// A better version, using the byte literal:
1688     ///
1689     /// ```rust,ignore
1690     /// b'x'
1691     /// ```
1692     pub CHAR_LIT_AS_U8,
1693     complexity,
1694     "casting a character literal to `u8` truncates"
1695 }
1696
1697 declare_lint_pass!(CharLitAsU8 => [CHAR_LIT_AS_U8]);
1698
1699 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for CharLitAsU8 {
1700     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1701         if_chain! {
1702             if !expr.span.from_expansion();
1703             if let ExprKind::Cast(e, _) = &expr.kind;
1704             if let ExprKind::Lit(l) = &e.kind;
1705             if let LitKind::Char(c) = l.node;
1706             if ty::Uint(UintTy::U8) == cx.tables.expr_ty(expr).kind;
1707             then {
1708                 let mut applicability = Applicability::MachineApplicable;
1709                 let snippet = snippet_with_applicability(cx, e.span, "'x'", &mut applicability);
1710
1711                 span_lint_and_then(
1712                     cx,
1713                     CHAR_LIT_AS_U8,
1714                     expr.span,
1715                     "casting a character literal to `u8` truncates",
1716                     |db| {
1717                         db.note("`char` is four bytes wide, but `u8` is a single byte");
1718
1719                         if c.is_ascii() {
1720                             db.span_suggestion(
1721                                 expr.span,
1722                                 "use a byte literal instead",
1723                                 format!("b{}", snippet),
1724                                 applicability,
1725                             );
1726                         }
1727                 });
1728             }
1729         }
1730     }
1731 }
1732
1733 declare_clippy_lint! {
1734     /// **What it does:** Checks for comparisons where one side of the relation is
1735     /// either the minimum or maximum value for its type and warns if it involves a
1736     /// case that is always true or always false. Only integer and boolean types are
1737     /// checked.
1738     ///
1739     /// **Why is this bad?** An expression like `min <= x` may misleadingly imply
1740     /// that it is possible for `x` to be less than the minimum. Expressions like
1741     /// `max < x` are probably mistakes.
1742     ///
1743     /// **Known problems:** For `usize` the size of the current compile target will
1744     /// be assumed (e.g., 64 bits on 64 bit systems). This means code that uses such
1745     /// a comparison to detect target pointer width will trigger this lint. One can
1746     /// use `mem::sizeof` and compare its value or conditional compilation
1747     /// attributes
1748     /// like `#[cfg(target_pointer_width = "64")] ..` instead.
1749     ///
1750     /// **Example:**
1751     ///
1752     /// ```rust
1753     /// let vec: Vec<isize> = Vec::new();
1754     /// if vec.len() <= 0 {}
1755     /// if 100 > std::i32::MAX {}
1756     /// ```
1757     pub ABSURD_EXTREME_COMPARISONS,
1758     correctness,
1759     "a comparison with a maximum or minimum value that is always true or false"
1760 }
1761
1762 declare_lint_pass!(AbsurdExtremeComparisons => [ABSURD_EXTREME_COMPARISONS]);
1763
1764 enum ExtremeType {
1765     Minimum,
1766     Maximum,
1767 }
1768
1769 struct ExtremeExpr<'a> {
1770     which: ExtremeType,
1771     expr: &'a Expr<'a>,
1772 }
1773
1774 enum AbsurdComparisonResult {
1775     AlwaysFalse,
1776     AlwaysTrue,
1777     InequalityImpossible,
1778 }
1779
1780 fn is_cast_between_fixed_and_target<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
1781     if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
1782         let precast_ty = cx.tables.expr_ty(cast_exp);
1783         let cast_ty = cx.tables.expr_ty(expr);
1784
1785         return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty);
1786     }
1787
1788     false
1789 }
1790
1791 fn detect_absurd_comparison<'a, 'tcx>(
1792     cx: &LateContext<'a, 'tcx>,
1793     op: BinOpKind,
1794     lhs: &'tcx Expr<'_>,
1795     rhs: &'tcx Expr<'_>,
1796 ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> {
1797     use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
1798     use crate::types::ExtremeType::{Maximum, Minimum};
1799     use crate::utils::comparisons::{normalize_comparison, Rel};
1800
1801     // absurd comparison only makes sense on primitive types
1802     // primitive types don't implement comparison operators with each other
1803     if cx.tables.expr_ty(lhs) != cx.tables.expr_ty(rhs) {
1804         return None;
1805     }
1806
1807     // comparisons between fix sized types and target sized types are considered unanalyzable
1808     if is_cast_between_fixed_and_target(cx, lhs) || is_cast_between_fixed_and_target(cx, rhs) {
1809         return None;
1810     }
1811
1812     let (rel, normalized_lhs, normalized_rhs) = normalize_comparison(op, lhs, rhs)?;
1813
1814     let lx = detect_extreme_expr(cx, normalized_lhs);
1815     let rx = detect_extreme_expr(cx, normalized_rhs);
1816
1817     Some(match rel {
1818         Rel::Lt => {
1819             match (lx, rx) {
1820                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x
1821                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min
1822                 _ => return None,
1823             }
1824         },
1825         Rel::Le => {
1826             match (lx, rx) {
1827                 (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x
1828                 (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x
1829                 (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min
1830                 (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max
1831                 _ => return None,
1832             }
1833         },
1834         Rel::Ne | Rel::Eq => return None,
1835     })
1836 }
1837
1838 fn detect_extreme_expr<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option<ExtremeExpr<'tcx>> {
1839     use crate::types::ExtremeType::{Maximum, Minimum};
1840
1841     let ty = cx.tables.expr_ty(expr);
1842
1843     let cv = constant(cx, cx.tables, expr)?.0;
1844
1845     let which = match (&ty.kind, cv) {
1846         (&ty::Bool, Constant::Bool(false)) | (&ty::Uint(_), Constant::Int(0)) => Minimum,
1847         (&ty::Int(ity), Constant::Int(i))
1848             if i == unsext(cx.tcx, i128::min_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1849         {
1850             Minimum
1851         },
1852
1853         (&ty::Bool, Constant::Bool(true)) => Maximum,
1854         (&ty::Int(ity), Constant::Int(i))
1855             if i == unsext(cx.tcx, i128::max_value() >> (128 - int_bits(cx.tcx, ity)), ity) =>
1856         {
1857             Maximum
1858         },
1859         (&ty::Uint(uty), Constant::Int(i)) if clip(cx.tcx, u128::max_value(), uty) == i => Maximum,
1860
1861         _ => return None,
1862     };
1863     Some(ExtremeExpr { which, expr })
1864 }
1865
1866 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AbsurdExtremeComparisons {
1867     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
1868         use crate::types::AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible};
1869         use crate::types::ExtremeType::{Maximum, Minimum};
1870
1871         if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
1872             if let Some((culprit, result)) = detect_absurd_comparison(cx, cmp.node, lhs, rhs) {
1873                 if !expr.span.from_expansion() {
1874                     let msg = "this comparison involving the minimum or maximum element for this \
1875                                type contains a case that is always true or always false";
1876
1877                     let conclusion = match result {
1878                         AlwaysFalse => "this comparison is always false".to_owned(),
1879                         AlwaysTrue => "this comparison is always true".to_owned(),
1880                         InequalityImpossible => format!(
1881                             "the case where the two sides are not equal never occurs, consider using `{} == {}` \
1882                              instead",
1883                             snippet(cx, lhs.span, "lhs"),
1884                             snippet(cx, rhs.span, "rhs")
1885                         ),
1886                     };
1887
1888                     let help = format!(
1889                         "because `{}` is the {} value for this type, {}",
1890                         snippet(cx, culprit.expr.span, "x"),
1891                         match culprit.which {
1892                             Minimum => "minimum",
1893                             Maximum => "maximum",
1894                         },
1895                         conclusion
1896                     );
1897
1898                     span_lint_and_help(cx, ABSURD_EXTREME_COMPARISONS, expr.span, msg, &help);
1899                 }
1900             }
1901         }
1902     }
1903 }
1904
1905 declare_clippy_lint! {
1906     /// **What it does:** Checks for comparisons where the relation is always either
1907     /// true or false, but where one side has been upcast so that the comparison is
1908     /// necessary. Only integer types are checked.
1909     ///
1910     /// **Why is this bad?** An expression like `let x : u8 = ...; (x as u32) > 300`
1911     /// will mistakenly imply that it is possible for `x` to be outside the range of
1912     /// `u8`.
1913     ///
1914     /// **Known problems:**
1915     /// https://github.com/rust-lang/rust-clippy/issues/886
1916     ///
1917     /// **Example:**
1918     /// ```rust
1919     /// let x: u8 = 1;
1920     /// (x as u32) > 300;
1921     /// ```
1922     pub INVALID_UPCAST_COMPARISONS,
1923     pedantic,
1924     "a comparison involving an upcast which is always true or false"
1925 }
1926
1927 declare_lint_pass!(InvalidUpcastComparisons => [INVALID_UPCAST_COMPARISONS]);
1928
1929 #[derive(Copy, Clone, Debug, Eq)]
1930 enum FullInt {
1931     S(i128),
1932     U(u128),
1933 }
1934
1935 impl FullInt {
1936     #[allow(clippy::cast_sign_loss)]
1937     #[must_use]
1938     fn cmp_s_u(s: i128, u: u128) -> Ordering {
1939         if s < 0 {
1940             Ordering::Less
1941         } else if u > (i128::max_value() as u128) {
1942             Ordering::Greater
1943         } else {
1944             (s as u128).cmp(&u)
1945         }
1946     }
1947 }
1948
1949 impl PartialEq for FullInt {
1950     #[must_use]
1951     fn eq(&self, other: &Self) -> bool {
1952         self.partial_cmp(other).expect("`partial_cmp` only returns `Some(_)`") == Ordering::Equal
1953     }
1954 }
1955
1956 impl PartialOrd for FullInt {
1957     #[must_use]
1958     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1959         Some(match (self, other) {
1960             (&Self::S(s), &Self::S(o)) => s.cmp(&o),
1961             (&Self::U(s), &Self::U(o)) => s.cmp(&o),
1962             (&Self::S(s), &Self::U(o)) => Self::cmp_s_u(s, o),
1963             (&Self::U(s), &Self::S(o)) => Self::cmp_s_u(o, s).reverse(),
1964         })
1965     }
1966 }
1967 impl Ord for FullInt {
1968     #[must_use]
1969     fn cmp(&self, other: &Self) -> Ordering {
1970         self.partial_cmp(other)
1971             .expect("`partial_cmp` for FullInt can never return `None`")
1972     }
1973 }
1974
1975 fn numeric_cast_precast_bounds<'a>(cx: &LateContext<'_, '_>, expr: &'a Expr<'_>) -> Option<(FullInt, FullInt)> {
1976     use std::{i128, i16, i32, i64, i8, isize, u128, u16, u32, u64, u8, usize};
1977
1978     if let ExprKind::Cast(ref cast_exp, _) = expr.kind {
1979         let pre_cast_ty = cx.tables.expr_ty(cast_exp);
1980         let cast_ty = cx.tables.expr_ty(expr);
1981         // if it's a cast from i32 to u32 wrapping will invalidate all these checks
1982         if cx.layout_of(pre_cast_ty).ok().map(|l| l.size) == cx.layout_of(cast_ty).ok().map(|l| l.size) {
1983             return None;
1984         }
1985         match pre_cast_ty.kind {
1986             ty::Int(int_ty) => Some(match int_ty {
1987                 IntTy::I8 => (
1988                     FullInt::S(i128::from(i8::min_value())),
1989                     FullInt::S(i128::from(i8::max_value())),
1990                 ),
1991                 IntTy::I16 => (
1992                     FullInt::S(i128::from(i16::min_value())),
1993                     FullInt::S(i128::from(i16::max_value())),
1994                 ),
1995                 IntTy::I32 => (
1996                     FullInt::S(i128::from(i32::min_value())),
1997                     FullInt::S(i128::from(i32::max_value())),
1998                 ),
1999                 IntTy::I64 => (
2000                     FullInt::S(i128::from(i64::min_value())),
2001                     FullInt::S(i128::from(i64::max_value())),
2002                 ),
2003                 IntTy::I128 => (FullInt::S(i128::min_value()), FullInt::S(i128::max_value())),
2004                 IntTy::Isize => (
2005                     FullInt::S(isize::min_value() as i128),
2006                     FullInt::S(isize::max_value() as i128),
2007                 ),
2008             }),
2009             ty::Uint(uint_ty) => Some(match uint_ty {
2010                 UintTy::U8 => (
2011                     FullInt::U(u128::from(u8::min_value())),
2012                     FullInt::U(u128::from(u8::max_value())),
2013                 ),
2014                 UintTy::U16 => (
2015                     FullInt::U(u128::from(u16::min_value())),
2016                     FullInt::U(u128::from(u16::max_value())),
2017                 ),
2018                 UintTy::U32 => (
2019                     FullInt::U(u128::from(u32::min_value())),
2020                     FullInt::U(u128::from(u32::max_value())),
2021                 ),
2022                 UintTy::U64 => (
2023                     FullInt::U(u128::from(u64::min_value())),
2024                     FullInt::U(u128::from(u64::max_value())),
2025                 ),
2026                 UintTy::U128 => (FullInt::U(u128::min_value()), FullInt::U(u128::max_value())),
2027                 UintTy::Usize => (
2028                     FullInt::U(usize::min_value() as u128),
2029                     FullInt::U(usize::max_value() as u128),
2030                 ),
2031             }),
2032             _ => None,
2033         }
2034     } else {
2035         None
2036     }
2037 }
2038
2039 fn node_as_const_fullint<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) -> Option<FullInt> {
2040     let val = constant(cx, cx.tables, expr)?.0;
2041     if let Constant::Int(const_int) = val {
2042         match cx.tables.expr_ty(expr).kind {
2043             ty::Int(ity) => Some(FullInt::S(sext(cx.tcx, const_int, ity))),
2044             ty::Uint(_) => Some(FullInt::U(const_int)),
2045             _ => None,
2046         }
2047     } else {
2048         None
2049     }
2050 }
2051
2052 fn err_upcast_comparison(cx: &LateContext<'_, '_>, span: Span, expr: &Expr<'_>, always: bool) {
2053     if let ExprKind::Cast(ref cast_val, _) = expr.kind {
2054         span_lint(
2055             cx,
2056             INVALID_UPCAST_COMPARISONS,
2057             span,
2058             &format!(
2059                 "because of the numeric bounds on `{}` prior to casting, this expression is always {}",
2060                 snippet(cx, cast_val.span, "the expression"),
2061                 if always { "true" } else { "false" },
2062             ),
2063         );
2064     }
2065 }
2066
2067 fn upcast_comparison_bounds_err<'a, 'tcx>(
2068     cx: &LateContext<'a, 'tcx>,
2069     span: Span,
2070     rel: comparisons::Rel,
2071     lhs_bounds: Option<(FullInt, FullInt)>,
2072     lhs: &'tcx Expr<'_>,
2073     rhs: &'tcx Expr<'_>,
2074     invert: bool,
2075 ) {
2076     use crate::utils::comparisons::Rel;
2077
2078     if let Some((lb, ub)) = lhs_bounds {
2079         if let Some(norm_rhs_val) = node_as_const_fullint(cx, rhs) {
2080             if rel == Rel::Eq || rel == Rel::Ne {
2081                 if norm_rhs_val < lb || norm_rhs_val > ub {
2082                     err_upcast_comparison(cx, span, lhs, rel == Rel::Ne);
2083                 }
2084             } else if match rel {
2085                 Rel::Lt => {
2086                     if invert {
2087                         norm_rhs_val < lb
2088                     } else {
2089                         ub < norm_rhs_val
2090                     }
2091                 },
2092                 Rel::Le => {
2093                     if invert {
2094                         norm_rhs_val <= lb
2095                     } else {
2096                         ub <= norm_rhs_val
2097                     }
2098                 },
2099                 Rel::Eq | Rel::Ne => unreachable!(),
2100             } {
2101                 err_upcast_comparison(cx, span, lhs, true)
2102             } else if match rel {
2103                 Rel::Lt => {
2104                     if invert {
2105                         norm_rhs_val >= ub
2106                     } else {
2107                         lb >= norm_rhs_val
2108                     }
2109                 },
2110                 Rel::Le => {
2111                     if invert {
2112                         norm_rhs_val > ub
2113                     } else {
2114                         lb > norm_rhs_val
2115                     }
2116                 },
2117                 Rel::Eq | Rel::Ne => unreachable!(),
2118             } {
2119                 err_upcast_comparison(cx, span, lhs, false)
2120             }
2121         }
2122     }
2123 }
2124
2125 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidUpcastComparisons {
2126     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
2127         if let ExprKind::Binary(ref cmp, ref lhs, ref rhs) = expr.kind {
2128             let normalized = comparisons::normalize_comparison(cmp.node, lhs, rhs);
2129             let (rel, normalized_lhs, normalized_rhs) = if let Some(val) = normalized {
2130                 val
2131             } else {
2132                 return;
2133             };
2134
2135             let lhs_bounds = numeric_cast_precast_bounds(cx, normalized_lhs);
2136             let rhs_bounds = numeric_cast_precast_bounds(cx, normalized_rhs);
2137
2138             upcast_comparison_bounds_err(cx, expr.span, rel, lhs_bounds, normalized_lhs, normalized_rhs, false);
2139             upcast_comparison_bounds_err(cx, expr.span, rel, rhs_bounds, normalized_rhs, normalized_lhs, true);
2140         }
2141     }
2142 }
2143
2144 declare_clippy_lint! {
2145     /// **What it does:** Checks for public `impl` or `fn` missing generalization
2146     /// over different hashers and implicitly defaulting to the default hashing
2147     /// algorithm (`SipHash`).
2148     ///
2149     /// **Why is this bad?** `HashMap` or `HashSet` with custom hashers cannot be
2150     /// used with them.
2151     ///
2152     /// **Known problems:** Suggestions for replacing constructors can contain
2153     /// false-positives. Also applying suggestions can require modification of other
2154     /// pieces of code, possibly including external crates.
2155     ///
2156     /// **Example:**
2157     /// ```rust
2158     /// # use std::collections::HashMap;
2159     /// # use std::hash::{Hash, BuildHasher};
2160     /// # trait Serialize {};
2161     /// impl<K: Hash + Eq, V> Serialize for HashMap<K, V> { }
2162     ///
2163     /// pub fn foo(map: &mut HashMap<i32, i32>) { }
2164     /// ```
2165     /// could be rewritten as
2166     /// ```rust
2167     /// # use std::collections::HashMap;
2168     /// # use std::hash::{Hash, BuildHasher};
2169     /// # trait Serialize {};
2170     /// impl<K: Hash + Eq, V, S: BuildHasher> Serialize for HashMap<K, V, S> { }
2171     ///
2172     /// pub fn foo<S: BuildHasher>(map: &mut HashMap<i32, i32, S>) { }
2173     /// ```
2174     pub IMPLICIT_HASHER,
2175     style,
2176     "missing generalization over different hashers"
2177 }
2178
2179 declare_lint_pass!(ImplicitHasher => [IMPLICIT_HASHER]);
2180
2181 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for ImplicitHasher {
2182     #[allow(clippy::cast_possible_truncation, clippy::too_many_lines)]
2183     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
2184         use rustc_span::BytePos;
2185
2186         fn suggestion<'a, 'tcx>(
2187             cx: &LateContext<'a, 'tcx>,
2188             db: &mut DiagnosticBuilder<'_>,
2189             generics_span: Span,
2190             generics_suggestion_span: Span,
2191             target: &ImplicitHasherType<'_>,
2192             vis: ImplicitHasherConstructorVisitor<'_, '_, '_>,
2193         ) {
2194             let generics_snip = snippet(cx, generics_span, "");
2195             // trim `<` `>`
2196             let generics_snip = if generics_snip.is_empty() {
2197                 ""
2198             } else {
2199                 &generics_snip[1..generics_snip.len() - 1]
2200             };
2201
2202             multispan_sugg(
2203                 db,
2204                 "consider adding a type parameter".to_string(),
2205                 vec![
2206                     (
2207                         generics_suggestion_span,
2208                         format!(
2209                             "<{}{}S: ::std::hash::BuildHasher{}>",
2210                             generics_snip,
2211                             if generics_snip.is_empty() { "" } else { ", " },
2212                             if vis.suggestions.is_empty() {
2213                                 ""
2214                             } else {
2215                                 // request users to add `Default` bound so that generic constructors can be used
2216                                 " + Default"
2217                             },
2218                         ),
2219                     ),
2220                     (
2221                         target.span(),
2222                         format!("{}<{}, S>", target.type_name(), target.type_arguments(),),
2223                     ),
2224                 ],
2225             );
2226
2227             if !vis.suggestions.is_empty() {
2228                 multispan_sugg(db, "...and use generic constructor".into(), vis.suggestions);
2229             }
2230         }
2231
2232         if !cx.access_levels.is_exported(item.hir_id) {
2233             return;
2234         }
2235
2236         match item.kind {
2237             ItemKind::Impl {
2238                 ref generics,
2239                 self_ty: ref ty,
2240                 ref items,
2241                 ..
2242             } => {
2243                 let mut vis = ImplicitHasherTypeVisitor::new(cx);
2244                 vis.visit_ty(ty);
2245
2246                 for target in &vis.found {
2247                     if differing_macro_contexts(item.span, target.span()) {
2248                         return;
2249                     }
2250
2251                     let generics_suggestion_span = generics.span.substitute_dummy({
2252                         let pos = snippet_opt(cx, item.span.until(target.span()))
2253                             .and_then(|snip| Some(item.span.lo() + BytePos(snip.find("impl")? as u32 + 4)));
2254                         if let Some(pos) = pos {
2255                             Span::new(pos, pos, item.span.data().ctxt)
2256                         } else {
2257                             return;
2258                         }
2259                     });
2260
2261                     let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2262                     for item in items.iter().map(|item| cx.tcx.hir().impl_item(item.id)) {
2263                         ctr_vis.visit_impl_item(item);
2264                     }
2265
2266                     span_lint_and_then(
2267                         cx,
2268                         IMPLICIT_HASHER,
2269                         target.span(),
2270                         &format!(
2271                             "impl for `{}` should be generalized over different hashers",
2272                             target.type_name()
2273                         ),
2274                         move |db| {
2275                             suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2276                         },
2277                     );
2278                 }
2279             },
2280             ItemKind::Fn(ref sig, ref generics, body_id) => {
2281                 let body = cx.tcx.hir().body(body_id);
2282
2283                 for ty in sig.decl.inputs {
2284                     let mut vis = ImplicitHasherTypeVisitor::new(cx);
2285                     vis.visit_ty(ty);
2286
2287                     for target in &vis.found {
2288                         if in_external_macro(cx.sess(), generics.span) {
2289                             continue;
2290                         }
2291                         let generics_suggestion_span = generics.span.substitute_dummy({
2292                             let pos = snippet_opt(cx, item.span.until(body.params[0].pat.span))
2293                                 .and_then(|snip| {
2294                                     let i = snip.find("fn")?;
2295                                     Some(item.span.lo() + BytePos((i + (&snip[i..]).find('(')?) as u32))
2296                                 })
2297                                 .expect("failed to create span for type parameters");
2298                             Span::new(pos, pos, item.span.data().ctxt)
2299                         });
2300
2301                         let mut ctr_vis = ImplicitHasherConstructorVisitor::new(cx, target);
2302                         ctr_vis.visit_body(body);
2303
2304                         span_lint_and_then(
2305                             cx,
2306                             IMPLICIT_HASHER,
2307                             target.span(),
2308                             &format!(
2309                                 "parameter of type `{}` should be generalized over different hashers",
2310                                 target.type_name()
2311                             ),
2312                             move |db| {
2313                                 suggestion(cx, db, generics.span, generics_suggestion_span, target, ctr_vis);
2314                             },
2315                         );
2316                     }
2317                 }
2318             },
2319             _ => {},
2320         }
2321     }
2322 }
2323
2324 enum ImplicitHasherType<'tcx> {
2325     HashMap(Span, Ty<'tcx>, Cow<'static, str>, Cow<'static, str>),
2326     HashSet(Span, Ty<'tcx>, Cow<'static, str>),
2327 }
2328
2329 impl<'tcx> ImplicitHasherType<'tcx> {
2330     /// Checks that `ty` is a target type without a `BuildHasher`.
2331     fn new<'a>(cx: &LateContext<'a, 'tcx>, hir_ty: &hir::Ty<'_>) -> Option<Self> {
2332         if let TyKind::Path(QPath::Resolved(None, ref path)) = hir_ty.kind {
2333             let params: Vec<_> = path
2334                 .segments
2335                 .last()
2336                 .as_ref()?
2337                 .args
2338                 .as_ref()?
2339                 .args
2340                 .iter()
2341                 .filter_map(|arg| match arg {
2342                     GenericArg::Type(ty) => Some(ty),
2343                     _ => None,
2344                 })
2345                 .collect();
2346             let params_len = params.len();
2347
2348             let ty = hir_ty_to_ty(cx.tcx, hir_ty);
2349
2350             if match_path(path, &paths::HASHMAP) && params_len == 2 {
2351                 Some(ImplicitHasherType::HashMap(
2352                     hir_ty.span,
2353                     ty,
2354                     snippet(cx, params[0].span, "K"),
2355                     snippet(cx, params[1].span, "V"),
2356                 ))
2357             } else if match_path(path, &paths::HASHSET) && params_len == 1 {
2358                 Some(ImplicitHasherType::HashSet(
2359                     hir_ty.span,
2360                     ty,
2361                     snippet(cx, params[0].span, "T"),
2362                 ))
2363             } else {
2364                 None
2365             }
2366         } else {
2367             None
2368         }
2369     }
2370
2371     fn type_name(&self) -> &'static str {
2372         match *self {
2373             ImplicitHasherType::HashMap(..) => "HashMap",
2374             ImplicitHasherType::HashSet(..) => "HashSet",
2375         }
2376     }
2377
2378     fn type_arguments(&self) -> String {
2379         match *self {
2380             ImplicitHasherType::HashMap(.., ref k, ref v) => format!("{}, {}", k, v),
2381             ImplicitHasherType::HashSet(.., ref t) => format!("{}", t),
2382         }
2383     }
2384
2385     fn ty(&self) -> Ty<'tcx> {
2386         match *self {
2387             ImplicitHasherType::HashMap(_, ty, ..) | ImplicitHasherType::HashSet(_, ty, ..) => ty,
2388         }
2389     }
2390
2391     fn span(&self) -> Span {
2392         match *self {
2393             ImplicitHasherType::HashMap(span, ..) | ImplicitHasherType::HashSet(span, ..) => span,
2394         }
2395     }
2396 }
2397
2398 struct ImplicitHasherTypeVisitor<'a, 'tcx> {
2399     cx: &'a LateContext<'a, 'tcx>,
2400     found: Vec<ImplicitHasherType<'tcx>>,
2401 }
2402
2403 impl<'a, 'tcx> ImplicitHasherTypeVisitor<'a, 'tcx> {
2404     fn new(cx: &'a LateContext<'a, 'tcx>) -> Self {
2405         Self { cx, found: vec![] }
2406     }
2407 }
2408
2409 impl<'a, 'tcx> Visitor<'tcx> for ImplicitHasherTypeVisitor<'a, 'tcx> {
2410     type Map = Map<'tcx>;
2411
2412     fn visit_ty(&mut self, t: &'tcx hir::Ty<'_>) {
2413         if let Some(target) = ImplicitHasherType::new(self.cx, t) {
2414             self.found.push(target);
2415         }
2416
2417         walk_ty(self, t);
2418     }
2419
2420     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2421         NestedVisitorMap::None
2422     }
2423 }
2424
2425 /// Looks for default-hasher-dependent constructors like `HashMap::new`.
2426 struct ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2427     cx: &'a LateContext<'a, 'tcx>,
2428     body: &'a TypeckTables<'tcx>,
2429     target: &'b ImplicitHasherType<'tcx>,
2430     suggestions: BTreeMap<Span, String>,
2431 }
2432
2433 impl<'a, 'b, 'tcx> ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2434     fn new(cx: &'a LateContext<'a, 'tcx>, target: &'b ImplicitHasherType<'tcx>) -> Self {
2435         Self {
2436             cx,
2437             body: cx.tables,
2438             target,
2439             suggestions: BTreeMap::new(),
2440         }
2441     }
2442 }
2443
2444 impl<'a, 'b, 'tcx> Visitor<'tcx> for ImplicitHasherConstructorVisitor<'a, 'b, 'tcx> {
2445     type Map = Map<'tcx>;
2446
2447     fn visit_body(&mut self, body: &'tcx Body<'_>) {
2448         let prev_body = self.body;
2449         self.body = self.cx.tcx.body_tables(body.id());
2450         walk_body(self, body);
2451         self.body = prev_body;
2452     }
2453
2454     fn visit_expr(&mut self, e: &'tcx Expr<'_>) {
2455         if_chain! {
2456             if let ExprKind::Call(ref fun, ref args) = e.kind;
2457             if let ExprKind::Path(QPath::TypeRelative(ref ty, ref method)) = fun.kind;
2458             if let TyKind::Path(QPath::Resolved(None, ref ty_path)) = ty.kind;
2459             then {
2460                 if !same_tys(self.cx, self.target.ty(), self.body.expr_ty(e)) {
2461                     return;
2462                 }
2463
2464                 if match_path(ty_path, &paths::HASHMAP) {
2465                     if method.ident.name == sym!(new) {
2466                         self.suggestions
2467                             .insert(e.span, "HashMap::default()".to_string());
2468                     } else if method.ident.name == sym!(with_capacity) {
2469                         self.suggestions.insert(
2470                             e.span,
2471                             format!(
2472                                 "HashMap::with_capacity_and_hasher({}, Default::default())",
2473                                 snippet(self.cx, args[0].span, "capacity"),
2474                             ),
2475                         );
2476                     }
2477                 } else if match_path(ty_path, &paths::HASHSET) {
2478                     if method.ident.name == sym!(new) {
2479                         self.suggestions
2480                             .insert(e.span, "HashSet::default()".to_string());
2481                     } else if method.ident.name == sym!(with_capacity) {
2482                         self.suggestions.insert(
2483                             e.span,
2484                             format!(
2485                                 "HashSet::with_capacity_and_hasher({}, Default::default())",
2486                                 snippet(self.cx, args[0].span, "capacity"),
2487                             ),
2488                         );
2489                     }
2490                 }
2491             }
2492         }
2493
2494         walk_expr(self, e);
2495     }
2496
2497     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
2498         NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
2499     }
2500 }
2501
2502 declare_clippy_lint! {
2503     /// **What it does:** Checks for casts of `&T` to `&mut T` anywhere in the code.
2504     ///
2505     /// **Why is this bad?** It’s basically guaranteed to be undefined behaviour.
2506     /// `UnsafeCell` is the only way to obtain aliasable data that is considered
2507     /// mutable.
2508     ///
2509     /// **Known problems:** None.
2510     ///
2511     /// **Example:**
2512     /// ```rust,ignore
2513     /// fn x(r: &i32) {
2514     ///     unsafe {
2515     ///         *(r as *const _ as *mut _) += 1;
2516     ///     }
2517     /// }
2518     /// ```
2519     ///
2520     /// Instead consider using interior mutability types.
2521     ///
2522     /// ```rust
2523     /// use std::cell::UnsafeCell;
2524     ///
2525     /// fn x(r: &UnsafeCell<i32>) {
2526     ///     unsafe {
2527     ///         *r.get() += 1;
2528     ///     }
2529     /// }
2530     /// ```
2531     pub CAST_REF_TO_MUT,
2532     correctness,
2533     "a cast of reference to a mutable pointer"
2534 }
2535
2536 declare_lint_pass!(RefToMut => [CAST_REF_TO_MUT]);
2537
2538 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for RefToMut {
2539     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
2540         if_chain! {
2541             if let ExprKind::Unary(UnOp::UnDeref, e) = &expr.kind;
2542             if let ExprKind::Cast(e, t) = &e.kind;
2543             if let TyKind::Ptr(MutTy { mutbl: Mutability::Mut, .. }) = t.kind;
2544             if let ExprKind::Cast(e, t) = &e.kind;
2545             if let TyKind::Ptr(MutTy { mutbl: Mutability::Not, .. }) = t.kind;
2546             if let ty::Ref(..) = cx.tables.node_type(e.hir_id).kind;
2547             then {
2548                 span_lint(
2549                     cx,
2550                     CAST_REF_TO_MUT,
2551                     expr.span,
2552                     "casting `&T` to `&mut T` may cause undefined behavior, consider instead using an `UnsafeCell`",
2553                 );
2554             }
2555         }
2556     }
2557 }