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