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