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