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