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