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