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