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