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