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