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