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