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