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