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