-use rustc::hir;
-use rustc::lint::*;
-use rustc::ty::{self, Ty};
-use rustc::hir::def::Def;
+use matches::matches;
+use crate::rustc::hir;
+use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass, in_external_macro, Lint, LintContext};
+use crate::rustc::{declare_tool_lint, lint_array};
+use if_chain::if_chain;
+use crate::rustc::ty::{self, Ty};
+use crate::rustc::hir::def::Def;
use std::borrow::Cow;
use std::fmt;
use std::iter;
-use syntax::ast;
-use syntax::codemap::{Span, BytePos};
-use crate::utils::{get_arg_name, get_trait_def_id, implements_trait, in_external_macro, in_macro, is_copy, is_expn_of, is_self,
+use crate::syntax::ast;
+use crate::syntax::source_map::{Span, BytePos};
+use crate::utils::{get_arg_name, get_trait_def_id, implements_trait, in_macro, is_copy, is_expn_of, is_self,
is_self_ty, iter_input_pats, last_path_segment, match_def_path, match_path, match_qpath, match_trait_method,
match_type, method_chain_args, match_var, return_ty, remove_blocks, same_tys, single_segment_path, snippet,
span_lint, span_lint_and_sugg, span_lint_and_then, span_note_and_lint, walk_ptrs_ty, walk_ptrs_ty_depth, SpanlessEq};
use crate::utils::paths;
use crate::utils::sugg;
use crate::consts::{constant, Constant};
+use crate::rustc_errors::Applicability;
#[derive(Clone)]
pub struct Pass;
///
/// **Example:**
/// ```rust
-/// foo.expect(&format("Err {}: {}", err_code, err_msg))
+/// foo.expect(&format!("Err {}: {}", err_code, err_msg))
/// ```
/// or
/// ```rust
-/// foo.expect(format("Err {}: {}", err_code, err_msg).as_str())
+/// foo.expect(format!("Err {}: {}", err_code, err_msg).as_str())
/// ```
/// this can instead be written:
/// ```rust
/// foo.unwrap_or_else(|_| panic!("Err {}: {}", err_code, err_msg))
/// ```
-/// or
-/// ```rust
-/// foo.unwrap_or_else(|_| panic!(format("Err {}: {}", err_code, err_msg).as_str()))
-/// ```
declare_clippy_lint! {
pub EXPECT_FUN_CALL,
perf,
/// (`Rc`, `Arc`, `rc::Weak`, or `sync::Weak`), and suggests calling Clone via unified
/// function syntax instead (e.g. `Rc::clone(foo)`).
///
-/// **Why is this bad?**: Calling '.clone()' on an Rc, Arc, or Weak
+/// **Why is this bad?** Calling '.clone()' on an Rc, Arc, or Weak
/// can obscure the fact that only the pointer is being cloned, not the underlying
/// data.
///
/// **Known problems:** Does not catch multi-byte unicode characters.
///
/// **Example:**
-/// `_.split("x")` could be `_.split('x')
+/// `_.split("x")` could be `_.split('x')`
declare_clippy_lint! {
pub SINGLE_CHAR_PATTERN,
perf,
/// ```rust,ignore
/// let c_str = CString::new("foo").unwrap().as_ptr();
/// unsafe {
-/// call_some_ffi_func(c_str);
+/// call_some_ffi_func(c_str);
/// }
/// ```
/// Here `c_str` point to a freed address. The correct use would be:
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
- #[allow(cyclomatic_complexity)]
+ #[allow(clippy::cyclomatic_complexity)]
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr) {
if in_macro(expr.span) {
return;
}
match self_ty.sty {
- ty::TyRef(_, ty, _) if ty.sty == ty::TyStr => for &(method, pos) in &PATTERN_METHODS {
+ ty::Ref(_, ty, _) if ty.sty == ty::Str => for &(method, pos) in &PATTERN_METHODS {
if method_call.ident.name == method && args.len() > pos {
lint_single_char_pattern(cx, expr, &args[pos]);
}
}
fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, implitem: &'tcx hir::ImplItem) {
- if in_external_macro(cx, implitem.span) {
+ if in_external_macro(cx.sess(), implitem.span) {
return;
}
let name = implitem.ident.name;
if let hir::ImplItemKind::Method(ref sig, id) = implitem.node;
if let Some(first_arg_ty) = sig.decl.inputs.get(0);
if let Some(first_arg) = iter_input_pats(&sig.decl, cx.tcx.hir.body(id)).next();
- if let hir::ItemImpl(_, _, _, _, None, ref self_ty, _) = item.node;
+ if let hir::ItemKind::Impl(_, _, _, _, None, ref self_ty, _) = item.node;
then {
if cx.access_levels.is_exported(implitem.id) {
// check missing trait implementations
}
/// Checks for the `OR_FUN_CALL` lint.
-fn lint_or_fun_call(cx: &LateContext, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
+fn lint_or_fun_call(cx: &LateContext<'_, '_>, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
/// Check for `unwrap_or(T::new())` or `unwrap_or(T::default())`.
fn check_unwrap_or_default(
- cx: &LateContext,
+ cx: &LateContext<'_, '_>,
name: &str,
fun: &hir::Expr,
self_expr: &hir::Expr,
}
/// Check for `*or(foo())`.
- #[allow(too_many_arguments)]
+ #[allow(clippy::too_many_arguments)]
fn check_general_case(
- cx: &LateContext,
+ cx: &LateContext<'_, '_>,
name: &str,
method_span: Span,
fun_span: Span,
return;
}
- let sugg: Cow<_> = match (fn_has_arguments, !or_has_args) {
+ let sugg: Cow<'_, _> = match (fn_has_arguments, !or_has_args) {
(true, _) => format!("|_| {}", snippet(cx, arg.span, "..")).into(),
(false, false) => format!("|| {}", snippet(cx, arg.span, "..")).into(),
(false, true) => snippet(cx, fun_span, ".."),
}
/// Checks for the `EXPECT_FUN_CALL` lint.
-fn lint_expect_fun_call(cx: &LateContext, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
+fn lint_expect_fun_call(cx: &LateContext<'_, '_>, expr: &hir::Expr, method_span: Span, name: &str, args: &[hir::Expr]) {
fn extract_format_args(arg: &hir::Expr) -> Option<&hir::HirVec<hir::Expr>> {
if let hir::ExprKind::AddrOf(_, ref addr_of) = arg.node {
if let hir::ExprKind::Call(ref inner_fun, ref inner_args) = addr_of.node {
None
}
- fn generate_format_arg_snippet(cx: &LateContext, a: &hir::Expr) -> String {
+ fn generate_format_arg_snippet(cx: &LateContext<'_, '_>, a: &hir::Expr) -> String {
if let hir::ExprKind::AddrOf(_, ref format_arg) = a.node {
if let hir::ExprKind::Match(ref format_arg_expr, _, _) = format_arg.node {
if let hir::ExprKind::Tup(ref format_arg_expr_tup) = format_arg_expr.node {
}
fn check_general_case(
- cx: &LateContext,
+ cx: &LateContext<'_, '_>,
name: &str,
method_span: Span,
self_expr: &hir::Expr,
return;
}
- // don't lint for constant values
- let owner_def = cx.tcx.hir.get_parent_did(arg.id);
- let promotable = cx.tcx.rvalue_promotable_map(owner_def).contains(&arg.hir_id.local_id);
- if promotable {
+ fn is_call(node: &hir::ExprKind) -> bool {
+ match node {
+ hir::ExprKind::AddrOf(_, expr) => {
+ is_call(&expr.node)
+ },
+ hir::ExprKind::Call(..)
+ | hir::ExprKind::MethodCall(..)
+ // These variants are debatable or require further examination
+ | hir::ExprKind::If(..)
+ | hir::ExprKind::Match(..) => true,
+ _ => false,
+ }
+ }
+
+ if !is_call(&arg.node) {
return;
}
return;
}
- let sugg: Cow<_> = snippet(cx, arg.span, "..");
+ let sugg: Cow<'_, _> = snippet(cx, arg.span, "..");
span_lint_and_sugg(
cx,
}
/// Checks for the `CLONE_ON_COPY` lint.
-fn lint_clone_on_copy(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty) {
+fn lint_clone_on_copy(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr, arg_ty: Ty<'_>) {
let ty = cx.tables.expr_ty(expr);
- if let ty::TyRef(_, inner, _) = arg_ty.sty {
- if let ty::TyRef(_, innermost, _) = inner.sty {
+ if let ty::Ref(_, inner, _) = arg_ty.sty {
+ if let ty::Ref(_, innermost, _) = inner.sty {
span_lint_and_then(
cx,
CLONE_DOUBLE_REF,
|db| if let Some(snip) = sugg::Sugg::hir_opt(cx, arg) {
let mut ty = innermost;
let mut n = 0;
- while let ty::TyRef(_, inner, _) = ty.sty {
+ while let ty::Ref(_, inner, _) = ty.sty {
ty = inner;
n += 1;
}
let refs: String = iter::repeat('&').take(n + 1).collect();
let derefs: String = iter::repeat('*').take(n).collect();
let explicit = format!("{}{}::clone({})", refs, ty, snip);
- db.span_suggestion(expr.span, "try dereferencing it", format!("{}({}{}).clone()", refs, derefs, snip.deref()));
- db.span_suggestion(expr.span, "or try being explicit about what type to clone", explicit);
+ db.span_suggestion_with_applicability(
+ expr.span,
+ "try dereferencing it",
+ format!("{}({}{}).clone()", refs, derefs, snip.deref()),
+ Applicability::Unspecified,
+ );
+ db.span_suggestion_with_applicability(
+ expr.span,
+ "or try being explicit about what type to clone",
+ explicit,
+ Applicability::Unspecified,
+ );
},
);
return; // don't report clone_on_copy
if is_copy(cx, ty) {
let snip;
if let Some(snippet) = sugg::Sugg::hir_opt(cx, arg) {
- if let ty::TyRef(..) = cx.tables.expr_ty(arg).sty {
+ if let ty::Ref(..) = cx.tables.expr_ty(arg).sty {
let parent = cx.tcx.hir.get_parent_node(expr.id);
match cx.tcx.hir.get(parent) {
- hir::map::NodeExpr(parent) => match parent.node {
+ hir::Node::Expr(parent) => match parent.node {
// &*x is a nop, &x.clone() is not
hir::ExprKind::AddrOf(..) |
// (*x).func() is useless, x.clone().func() can work in case func borrows mutably
hir::ExprKind::MethodCall(..) => return,
_ => {},
}
- hir::map::NodeStmt(stmt) => {
- if let hir::StmtDecl(ref decl, _) = stmt.node {
- if let hir::DeclLocal(ref loc) = decl.node {
+ hir::Node::Stmt(stmt) => {
+ if let hir::StmtKind::Decl(ref decl, _) = stmt.node {
+ if let hir::DeclKind::Local(ref loc) = decl.node {
if let hir::PatKind::Ref(..) = loc.pat.node {
// let ref y = *x borrows x, let ref y = x.clone() does not
return;
}
span_lint_and_then(cx, CLONE_ON_COPY, expr.span, "using `clone` on a `Copy` type", |db| {
if let Some((text, snip)) = snip {
- db.span_suggestion(expr.span, text, snip);
+ db.span_suggestion_with_applicability(
+ expr.span,
+ text,
+ snip,
+ Applicability::Unspecified,
+ );
}
});
}
}
-fn lint_clone_on_ref_ptr(cx: &LateContext, expr: &hir::Expr, arg: &hir::Expr) {
+fn lint_clone_on_ref_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, arg: &hir::Expr) {
let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(arg));
- if let ty::TyAdt(_, subst) = obj_ty.sty {
+ if let ty::Adt(_, subst) = obj_ty.sty {
let caller_type = if match_type(cx, obj_ty, &paths::RC) {
"Rc"
} else if match_type(cx, obj_ty, &paths::ARC) {
}
-fn lint_string_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
+fn lint_string_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
let arg = &args[1];
if let Some(arglists) = method_chain_args(arg, &["chars"]) {
let target = &arglists[0][0];
let self_ty = walk_ptrs_ty(cx.tables.expr_ty(target));
- let ref_str = if self_ty.sty == ty::TyStr {
+ let ref_str = if self_ty.sty == ty::Str {
""
} else if match_type(cx, self_ty, &paths::STRING) {
"&"
}
}
-fn lint_extend(cx: &LateContext, expr: &hir::Expr, args: &[hir::Expr]) {
+fn lint_extend(cx: &LateContext<'_, '_>, expr: &hir::Expr, args: &[hir::Expr]) {
let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&args[0]));
if match_type(cx, obj_ty, &paths::STRING) {
lint_string_extend(cx, expr, args);
}
}
-fn lint_cstring_as_ptr(cx: &LateContext, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
+fn lint_cstring_as_ptr(cx: &LateContext<'_, '_>, expr: &hir::Expr, new: &hir::Expr, unwrap: &hir::Expr) {
if_chain! {
if let hir::ExprKind::Call(ref fun, ref args) = new.node;
if args.len() == 1;
}
}
-fn lint_iter_cloned_collect(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr]) {
+fn lint_iter_cloned_collect(cx: &LateContext<'_, '_>, expr: &hir::Expr, iter_args: &[hir::Expr]) {
if match_type(cx, cx.tables.expr_ty(expr), &paths::VEC)
&& derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some()
{
}
}
-fn lint_unnecessary_fold(cx: &LateContext, expr: &hir::Expr, fold_args: &[hir::Expr]) {
+fn lint_unnecessary_fold(cx: &LateContext<'_, '_>, expr: &hir::Expr, fold_args: &[hir::Expr]) {
// Check that this is a call to Iterator::fold rather than just some function called fold
if !match_trait_method(cx, expr, &paths::ITERATOR) {
return;
"Expected fold_args to have three entries - the receiver, the initial value and the closure");
fn check_fold_with_op(
- cx: &LateContext,
+ cx: &LateContext<'_, '_>,
fold_args: &[hir::Expr],
op: hir::BinOpKind,
replacement_method_name: &str,
then {
// Span containing `.fold(...)`
- let next_point = cx.sess().codemap().next_point(fold_args[0].span);
+ let next_point = cx.sess().source_map().next_point(fold_args[0].span);
let fold_span = next_point.with_hi(fold_args[2].span.hi() + BytePos(1));
let sugg = if replacement_has_args {
cx, fold_args, hir::BinOpKind::And, "all", true
),
ast::LitKind::Int(0, _) => check_fold_with_op(
- cx, fold_args, hir::BinOpKindAdd, "sum", false
+ cx, fold_args, hir::BinOpKind::Add, "sum", false
),
ast::LitKind::Int(1, _) => check_fold_with_op(
cx, fold_args, hir::BinOpKind::Mul, "product", false
};
}
-fn lint_iter_nth(cx: &LateContext, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
+fn lint_iter_nth(cx: &LateContext<'_, '_>, expr: &hir::Expr, iter_args: &[hir::Expr], is_mut: bool) {
let mut_str = if is_mut { "_mut" } else { "" };
let caller_type = if derefs_to_slice(cx, &iter_args[0], cx.tables.expr_ty(&iter_args[0])).is_some() {
"slice"
);
}
-fn lint_get_unwrap(cx: &LateContext, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
+fn lint_get_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr, get_args: &[hir::Expr], is_mut: bool) {
// Note: we don't want to lint `get_mut().unwrap` for HashMap or BTreeMap,
// because they do not implement `IndexMut`
let expr_ty = cx.tables.expr_ty(&get_args[0]);
);
}
-fn lint_iter_skip_next(cx: &LateContext, expr: &hir::Expr) {
+fn lint_iter_skip_next(cx: &LateContext<'_, '_>, expr: &hir::Expr) {
// lint if caller of skip is an Iterator
if match_trait_method(cx, expr, &paths::ITERATOR) {
span_lint(
}
}
-fn derefs_to_slice(cx: &LateContext, expr: &hir::Expr, ty: Ty) -> Option<sugg::Sugg<'static>> {
- fn may_slice(cx: &LateContext, ty: Ty) -> bool {
+fn derefs_to_slice(cx: &LateContext<'_, '_>, expr: &hir::Expr, ty: Ty<'_>) -> Option<sugg::Sugg<'static>> {
+ fn may_slice(cx: &LateContext<'_, '_>, ty: Ty<'_>) -> bool {
match ty.sty {
- ty::TySlice(_) => true,
- ty::TyAdt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
- ty::TyAdt(..) => match_type(cx, ty, &paths::VEC),
- ty::TyArray(_, size) => size.assert_usize(cx.tcx).expect("array length") < 32,
- ty::TyRef(_, inner, _) => may_slice(cx, inner),
+ ty::Slice(_) => true,
+ ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()),
+ ty::Adt(..) => match_type(cx, ty, &paths::VEC),
+ ty::Array(_, size) => size.assert_usize(cx.tcx).expect("array length") < 32,
+ ty::Ref(_, inner, _) => may_slice(cx, inner),
_ => false,
}
}
}
} else {
match ty.sty {
- ty::TySlice(_) => sugg::Sugg::hir_opt(cx, expr),
- ty::TyAdt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
- ty::TyRef(_, inner, _) => if may_slice(cx, inner) {
+ ty::Slice(_) => sugg::Sugg::hir_opt(cx, expr),
+ ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => sugg::Sugg::hir_opt(cx, expr),
+ ty::Ref(_, inner, _) => if may_slice(cx, inner) {
sugg::Sugg::hir_opt(cx, expr)
} else {
None
}
/// lint use of `unwrap()` for `Option`s and `Result`s
-fn lint_unwrap(cx: &LateContext, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
+fn lint_unwrap(cx: &LateContext<'_, '_>, expr: &hir::Expr, unwrap_args: &[hir::Expr]) {
let obj_ty = walk_ptrs_ty(cx.tables.expr_ty(&unwrap_args[0]));
let mess = if match_type(cx, obj_ty, &paths::OPTION) {
}
/// lint use of `ok().expect()` for `Result`s
-fn lint_ok_expect(cx: &LateContext, expr: &hir::Expr, ok_args: &[hir::Expr]) {
+fn lint_ok_expect(cx: &LateContext<'_, '_>, expr: &hir::Expr, ok_args: &[hir::Expr]) {
// lint if the caller of `ok()` is a `Result`
if match_type(cx, cx.tables.expr_ty(&ok_args[0]), &paths::RESULT) {
let result_type = cx.tables.expr_ty(&ok_args[0]);
}
/// lint use of `map().unwrap_or()` for `Option`s
-fn lint_map_unwrap_or(cx: &LateContext, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
+fn lint_map_unwrap_or(cx: &LateContext<'_, '_>, expr: &hir::Expr, map_args: &[hir::Expr], unwrap_args: &[hir::Expr]) {
// lint if the caller of `map()` is an `Option`
if match_type(cx, cx.tables.expr_ty(&map_args[0]), &paths::OPTION) {
// get snippets for args to map() and unwrap_or()
let map_or_func_snippet = snippet(cx, map_or_args[2].span, "..");
let hint = format!("{0}.and_then({1})", map_or_self_snippet, map_or_func_snippet);
span_lint_and_then(cx, OPTION_MAP_OR_NONE, expr.span, msg, |db| {
- db.span_suggestion(expr.span, "try using and_then instead", hint);
+ db.span_suggestion_with_applicability(
+ expr.span,
+ "try using and_then instead",
+ hint,
+ Applicability::Unspecified,
+ );
});
}
}
}
/// Checks for the `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints.
-fn lint_binary_expr_with_method_call<'a, 'tcx: 'a>(cx: &LateContext<'a, 'tcx>, info: &mut BinaryExprInfo) {
+fn lint_binary_expr_with_method_call(cx: &LateContext<'_, '_>, info: &mut BinaryExprInfo<'_>) {
macro_rules! lint_with_both_lhs_and_rhs {
($func:ident, $cx:expr, $info:ident) => {
if !$func($cx, $info) {
}
/// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_NEXT_CMP` lints.
-fn lint_chars_cmp<'a, 'tcx>(
- cx: &LateContext<'a, 'tcx>,
- info: &BinaryExprInfo,
+fn lint_chars_cmp(
+ cx: &LateContext<'_, '_>,
+ info: &BinaryExprInfo<'_>,
chain_methods: &[&str],
lint: &'static Lint,
suggest: &str,
then {
let self_ty = walk_ptrs_ty(cx.tables.expr_ty_adjusted(&args[0][0]));
- if self_ty.sty != ty::TyStr {
+ if self_ty.sty != ty::Str {
return false;
}
}
/// Checks for the `CHARS_NEXT_CMP` lint.
-fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
+fn lint_chars_next_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
lint_chars_cmp(cx, info, &["chars", "next"], CHARS_NEXT_CMP, "starts_with")
}
/// Checks for the `CHARS_LAST_CMP` lint.
-fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
+fn lint_chars_last_cmp<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
if lint_chars_cmp(cx, info, &["chars", "last"], CHARS_NEXT_CMP, "ends_with") {
true
} else {
/// Wrapper fn for `CHARS_NEXT_CMP` and `CHARS_LAST_CMP` lints with `unwrap()`.
fn lint_chars_cmp_with_unwrap<'a, 'tcx>(
cx: &LateContext<'a, 'tcx>,
- info: &BinaryExprInfo,
+ info: &BinaryExprInfo<'_>,
chain_methods: &[&str],
lint: &'static Lint,
suggest: &str,
}
/// Checks for the `CHARS_NEXT_CMP` lint with `unwrap()`.
-fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
+fn lint_chars_next_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
lint_chars_cmp_with_unwrap(cx, info, &["chars", "next", "unwrap"], CHARS_NEXT_CMP, "starts_with")
}
/// Checks for the `CHARS_LAST_CMP` lint with `unwrap()`.
-fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo) -> bool {
+fn lint_chars_last_cmp_with_unwrap<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, info: &BinaryExprInfo<'_>) -> bool {
if lint_chars_cmp_with_unwrap(cx, info, &["chars", "last", "unwrap"], CHARS_LAST_CMP, "ends_with") {
true
} else {
}
/// lint for length-1 `str`s for methods in `PATTERN_METHODS`
-fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
+fn lint_single_char_pattern<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, _expr: &'tcx hir::Expr, arg: &'tcx hir::Expr) {
if let Some((Constant::Str(r), _)) = constant(cx, cx.tables, arg) {
if r.len() == 1 {
- let c = r.chars().next().unwrap();
- let snip = snippet(cx, expr.span, "..");
- let hint = snip.replace(
- &format!("\"{}\"", c.escape_default()),
- &format!("'{}'", c.escape_default()));
- span_lint_and_then(
+ let snip = snippet(cx, arg.span, "..");
+ let hint = format!("'{}'", &snip[1..snip.len() - 1]);
+ span_lint_and_sugg(
cx,
SINGLE_CHAR_PATTERN,
arg.span,
"single-character string constant used as pattern",
- |db| {
- db.span_suggestion(expr.span, "try using a char instead", hint);
- },
+ "try using a char instead",
+ hint,
);
}
}
}
/// Checks for the `USELESS_ASREF` lint.
-fn lint_asref(cx: &LateContext, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
+fn lint_asref(cx: &LateContext<'_, '_>, expr: &hir::Expr, call_name: &str, as_ref_args: &[hir::Expr]) {
// when we get here, we've already checked that the call name is "as_ref" or "as_mut"
// check if the call is to the actual `AsRef` or `AsMut` trait
if match_trait_method(cx, expr, &paths::ASREF_TRAIT) || match_trait_method(cx, expr, &paths::ASMUT_TRAIT) {
}
/// Given a `Result<T, E>` type, return its error type (`E`).
-fn get_error_type<'a>(cx: &LateContext, ty: Ty<'a>) -> Option<Ty<'a>> {
- if let ty::TyAdt(_, substs) = ty.sty {
+fn get_error_type<'a>(cx: &LateContext<'_, '_>, ty: Ty<'a>) -> Option<Ty<'a>> {
+ if let ty::Adt(_, substs) = ty.sty {
if match_type(cx, ty, &paths::RESULT) {
substs.types().nth(1)
} else {
StartsWith(&'static str),
}
-#[cfg_attr(rustfmt, rustfmt_skip)]
+#[rustfmt::skip]
const CONVENTIONS: [(Convention, &[SelfKind]); 6] = [
(Convention::Eq("new"), &[SelfKind::No]),
(Convention::StartsWith("as_"), &[SelfKind::Ref, SelfKind::RefMut]),
(Convention::StartsWith("to_"), &[SelfKind::Ref]),
];
-#[cfg_attr(rustfmt, rustfmt_skip)]
+#[rustfmt::skip]
const TRAIT_METHODS: [(&str, usize, SelfKind, OutType, &str); 30] = [
("add", 2, SelfKind::Value, OutType::Any, "std::ops::Add"),
("as_mut", 1, SelfKind::RefMut, OutType::Ref, "std::convert::AsMut"),
("sub", 2, SelfKind::Value, OutType::Any, "std::ops::Sub"),
];
-#[cfg_attr(rustfmt, rustfmt_skip)]
+#[rustfmt::skip]
const PATTERN_METHODS: [(&str, usize); 17] = [
("contains", 1),
("starts_with", 1),
impl SelfKind {
fn matches(
self,
- cx: &LateContext,
+ cx: &LateContext<'_, '_>,
ty: &hir::Ty,
arg: &hir::Arg,
self_ty: &hir::Ty,
}
impl fmt::Display for Convention {
- fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match *self {
Convention::Eq(this) => this.fmt(f),
Convention::StartsWith(this) => this.fmt(f).and_then(|_| '*'.fmt(f)),
}
impl OutType {
- fn matches(self, cx: &LateContext, ty: &hir::FunctionRetTy) -> bool {
- let is_unit = |ty: &hir::Ty| SpanlessEq::new(cx).eq_ty_kind(&ty.node, &hir::TyTup(vec![].into()));
+ fn matches(self, cx: &LateContext<'_, '_>, ty: &hir::FunctionRetTy) -> bool {
+ let is_unit = |ty: &hir::Ty| SpanlessEq::new(cx).eq_ty_kind(&ty.node, &hir::TyKind::Tup(vec![].into()));
match (self, ty) {
(OutType::Unit, &hir::DefaultReturn(_)) => true,
(OutType::Unit, &hir::Return(ref ty)) if is_unit(ty) => true,