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