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