diff options
| author | Takayuki Maeda <takoyaki0316@gmail.com> | 2021-03-17 14:45:20 +0900 |
|---|---|---|
| committer | Takayuki Maeda <takoyaki0316@gmail.com> | 2021-03-18 00:59:45 +0900 |
| commit | 602bcf3e4f5f540e2f81d9e807e28b35c7bee0ed (patch) | |
| tree | 370d2e005ba86d984086de6a3cc8ad0d5d10e58d /clippy_lints/src/methods/utils.rs | |
| parent | 27963c8dce5b2db8c6c308681682bbb33938e125 (diff) | |
move get_hint_if_single_char_arg to methods/utils.rs
Diffstat (limited to 'clippy_lints/src/methods/utils.rs')
| -rw-r--r-- | clippy_lints/src/methods/utils.rs | 34 |
1 files changed, 33 insertions, 1 deletions
diff --git a/clippy_lints/src/methods/utils.rs b/clippy_lints/src/methods/utils.rs index 4d801148cbc..8de23e1bc6e 100644 --- a/clippy_lints/src/methods/utils.rs +++ b/clippy_lints/src/methods/utils.rs @@ -1,11 +1,15 @@ +use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::is_type_diagnostic_item; +use if_chain::if_chain; +use rustc_ast::ast; +use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateContext; use rustc_middle::ty; use rustc_middle::ty::Ty; use rustc_span::symbol::sym; -pub fn derefs_to_slice<'tcx>( +pub(super) fn derefs_to_slice<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>, ty: Ty<'tcx>, @@ -44,3 +48,31 @@ pub fn derefs_to_slice<'tcx>( } } } + +pub(super) fn get_hint_if_single_char_arg( + cx: &LateContext<'_>, + arg: &hir::Expr<'_>, + applicability: &mut Applicability, +) -> Option<String> { + if_chain! { + if let hir::ExprKind::Lit(lit) = &arg.kind; + if let ast::LitKind::Str(r, style) = lit.node; + let string = r.as_str(); + if string.chars().count() == 1; + then { + let snip = snippet_with_applicability(cx, arg.span, &string, applicability); + let ch = if let ast::StrStyle::Raw(nhash) = style { + let nhash = nhash as usize; + // for raw string: r##"a"## + &snip[(nhash + 2)..(snip.len() - 1 - nhash)] + } else { + // for regular string: "a" + &snip[1..(snip.len() - 1)] + }; + let hint = format!("'{}'", if ch == "'" { "\\'" } else { ch }); + Some(hint) + } else { + None + } + } +} |
