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