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