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