]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/methods/utils.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / clippy_lints / src / methods / utils.rs
1 use clippy_utils::source::snippet_with_applicability;
2 use clippy_utils::ty::is_type_diagnostic_item;
3 use if_chain::if_chain;
4 use rustc_ast::ast;
5 use rustc_errors::Applicability;
6 use rustc_hir as hir;
7 use rustc_lint::LateContext;
8 use rustc_middle::ty::{self, Ty};
9 use rustc_span::symbol::sym;
10
11 pub(super) fn derefs_to_slice<'tcx>(
12     cx: &LateContext<'tcx>,
13     expr: &'tcx hir::Expr<'tcx>,
14     ty: Ty<'tcx>,
15 ) -> Option<&'tcx hir::Expr<'tcx>> {
16     fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool {
17         match ty.kind() {
18             ty::Slice(_) => true,
19             ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
20             ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym::vec_type),
21             ty::Array(_, size) => size
22                 .try_eval_usize(cx.tcx, cx.param_env)
23                 .map_or(false, |size| size < 32),
24             ty::Ref(_, inner, _) => may_slice(cx, inner),
25             _ => false,
26         }
27     }
28
29     if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind {
30         if path.ident.name == sym::iter && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) {
31             Some(&args[0])
32         } else {
33             None
34         }
35     } else {
36         match ty.kind() {
37             ty::Slice(_) => Some(expr),
38             ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr),
39             ty::Ref(_, inner, _) => {
40                 if may_slice(cx, inner) {
41                     Some(expr)
42                 } else {
43                     None
44                 }
45             },
46             _ => None,
47         }
48     }
49 }
50
51 pub(super) fn get_hint_if_single_char_arg(
52     cx: &LateContext<'_>,
53     arg: &hir::Expr<'_>,
54     applicability: &mut Applicability,
55 ) -> Option<String> {
56     if_chain! {
57         if let hir::ExprKind::Lit(lit) = &arg.kind;
58         if let ast::LitKind::Str(r, style) = lit.node;
59         let string = r.as_str();
60         if string.chars().count() == 1;
61         then {
62             let snip = snippet_with_applicability(cx, arg.span, &string, applicability);
63             let ch = if let ast::StrStyle::Raw(nhash) = style {
64                 let nhash = nhash as usize;
65                 // for raw string: r##"a"##
66                 &snip[(nhash + 2)..(snip.len() - 1 - nhash)]
67             } else {
68                 // for regular string: "a"
69                 &snip[1..(snip.len() - 1)]
70             };
71             let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch });
72             Some(hint)
73         } else {
74             None
75         }
76     }
77 }