Skip to content

Commit

Permalink
Auto merge of #5951 - ThibsG:FixMacroCloneOnRefPtr2076, r=ebroto
Browse files Browse the repository at this point in the history
Fix incorrect suggestion when `clone_on_ref_ptr` is triggered in macros

In the lint `clone_on_ref_ptr`, if the `span` is in a macro, don't expand it for suggestion.

Fixes: #2076

changelog: none

r? @ebroto
  • Loading branch information
bors committed Aug 25, 2020
2 parents e191151 + 370fc45 commit ad7a03c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 7 deletions.
9 changes: 3 additions & 6 deletions clippy_lints/src/methods/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2150,18 +2150,15 @@ fn lint_clone_on_ref_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>, arg: &hir::
return;
};

let snippet = snippet_with_macro_callsite(cx, arg.span, "_");

span_lint_and_sugg(
cx,
CLONE_ON_REF_PTR,
expr.span,
"using `.clone()` on a ref-counted pointer",
"try this",
format!(
"{}::<{}>::clone(&{})",
caller_type,
subst.type_at(0),
snippet(cx, arg.span, "_")
),
format!("{}::<{}>::clone(&{})", caller_type, subst.type_at(0), snippet),
Applicability::Unspecified, // Sometimes unnecessary ::<_> after Rc/Arc/Weak
);
}
Expand Down
18 changes: 18 additions & 0 deletions tests/ui/unnecessary_clone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,21 @@ mod many_derefs {
let _ = &encoded.clone();
}
}

mod issue2076 {
use std::rc::Rc;

macro_rules! try_opt {
($expr: expr) => {
match $expr {
Some(value) => value,
None => return None,
}
};
}

fn func() -> Option<Rc<u8>> {
let rc = Rc::new(42);
Some(try_opt!(Some(rc)).clone())
}
}
8 changes: 7 additions & 1 deletion tests/ui/unnecessary_clone.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -96,5 +96,11 @@ help: or try being explicit if you are sure, that you want to clone a reference
LL | let _ = &<&[u8]>::clone(encoded);
| ^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to 11 previous errors
error: using `.clone()` on a ref-counted pointer
--> $DIR/unnecessary_clone.rs:108:14
|
LL | Some(try_opt!(Some(rc)).clone())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `Rc::<u8>::clone(&try_opt!(Some(rc)))`

error: aborting due to 12 previous errors

0 comments on commit ad7a03c

Please sign in to comment.