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