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