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