2020-10-28 17:36:07 -05:00
|
|
|
use std::cmp;
|
2021-03-08 17:57:44 -06:00
|
|
|
use std::iter;
|
2020-10-28 17:36:07 -05:00
|
|
|
|
2021-03-25 13:29:11 -05:00
|
|
|
use clippy_utils::diagnostics::span_lint_and_sugg;
|
|
|
|
use clippy_utils::source::snippet;
|
|
|
|
use clippy_utils::ty::is_copy;
|
2021-08-12 04:16:25 -05:00
|
|
|
use clippy_utils::{is_self, is_self_ty};
|
2020-10-28 17:36:07 -05:00
|
|
|
use if_chain::if_chain;
|
|
|
|
use rustc_ast::attr;
|
|
|
|
use rustc_errors::Applicability;
|
|
|
|
use rustc_hir as hir;
|
|
|
|
use rustc_hir::intravisit::FnKind;
|
2021-01-15 03:56:44 -06:00
|
|
|
use rustc_hir::{BindingAnnotation, Body, FnDecl, HirId, Impl, ItemKind, MutTy, Mutability, Node, PatKind};
|
2020-10-28 17:36:07 -05:00
|
|
|
use rustc_lint::{LateContext, LateLintPass};
|
|
|
|
use rustc_middle::ty;
|
2021-08-30 09:38:27 -05:00
|
|
|
use rustc_middle::ty::layout::LayoutOf;
|
2020-10-28 17:36:07 -05:00
|
|
|
use rustc_session::{declare_tool_lint, impl_lint_pass};
|
2021-07-28 17:07:32 -05:00
|
|
|
use rustc_span::def_id::LocalDefId;
|
2020-11-05 07:29:48 -06:00
|
|
|
use rustc_span::{sym, Span};
|
2020-10-28 17:36:07 -05:00
|
|
|
use rustc_target::spec::abi::Abi;
|
|
|
|
use rustc_target::spec::Target;
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for functions taking arguments by reference, where
|
2020-10-28 17:36:07 -05:00
|
|
|
/// the argument type is `Copy` and small enough to be more efficient to always
|
|
|
|
/// pass by value.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// In many calling conventions instances of structs will
|
2020-10-28 17:36:07 -05:00
|
|
|
/// be passed through registers if they fit into two or less general purpose
|
|
|
|
/// registers.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Known problems
|
|
|
|
/// This lint is target register size dependent, it is
|
2020-10-28 17:36:07 -05:00
|
|
|
/// limited to 32-bit to try and reduce portability problems between 32 and
|
|
|
|
/// 64-bit, but if you are compiling for 8 or 16-bit targets then the limit
|
|
|
|
/// will be different.
|
|
|
|
///
|
|
|
|
/// The configuration option `trivial_copy_size_limit` can be set to override
|
|
|
|
/// this limit for a project.
|
|
|
|
///
|
|
|
|
/// This lint attempts to allow passing arguments by reference if a reference
|
|
|
|
/// to that argument is returned. This is implemented by comparing the lifetime
|
|
|
|
/// of the argument and return value for equality. However, this can cause
|
|
|
|
/// false positives in cases involving multiple lifetimes that are bounded by
|
|
|
|
/// each other.
|
|
|
|
///
|
2021-04-22 04:31:13 -05:00
|
|
|
/// Also, it does not take account of other similar cases where getting memory addresses
|
|
|
|
/// matters; namely, returning the pointer to the argument in question,
|
|
|
|
/// and passing the argument, as both references and pointers,
|
|
|
|
/// to a function that needs the memory address. For further details, refer to
|
|
|
|
/// [this issue](https://github.com/rust-lang/rust-clippy/issues/5953)
|
|
|
|
/// that explains a real case in which this false positive
|
|
|
|
/// led to an **undefined behaviour** introduced with unsafe code.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2020-10-28 17:36:07 -05:00
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// // Bad
|
|
|
|
/// fn foo(v: &u32) {}
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// // Better
|
|
|
|
/// fn foo(v: u32) {}
|
|
|
|
/// ```
|
Added `clippy::version` attribute to all normal lints
So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`...
And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun...
Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work.
```nu
mv v0.0.212 rust-1.00.0;
mv beta rust-1.57.0;
mv master rust-1.58.0;
let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path);
let versions = (
ls | where name =~ "rust-" | select name | format {name}/lints.json |
each { open $it | select id | insert version $it | str substring "5,11" version} |
group-by id | rotate counter-clockwise id version |
update version {get version | first 1} | flatten | select id version);
$paths | each { |row|
let version = ($versions | where id == ($row.id) | format {version})
let idu = ($row.id | str upcase)
$"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)"
} | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh";
```
And this still has some problems, but at this point I just want to be done -.-
2021-10-21 14:06:26 -05:00
|
|
|
#[clippy::version = "pre 1.29.0"]
|
2020-10-28 17:36:07 -05:00
|
|
|
pub TRIVIALLY_COPY_PASS_BY_REF,
|
|
|
|
pedantic,
|
|
|
|
"functions taking small copyable arguments by reference"
|
|
|
|
}
|
|
|
|
|
|
|
|
declare_clippy_lint! {
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### What it does
|
|
|
|
/// Checks for functions taking arguments by value, where
|
2020-10-28 17:36:07 -05:00
|
|
|
/// the argument type is `Copy` and large enough to be worth considering
|
|
|
|
/// passing by reference. Does not trigger if the function is being exported,
|
|
|
|
/// because that might induce API breakage, if the parameter is declared as mutable,
|
|
|
|
/// or if the argument is a `self`.
|
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Why is this bad?
|
|
|
|
/// Arguments passed by value might result in an unnecessary
|
2020-10-28 17:36:07 -05:00
|
|
|
/// shallow copy, taking up more space in the stack and requiring a call to
|
2021-01-15 03:56:44 -06:00
|
|
|
/// `memcpy`, which can be expensive.
|
2020-10-28 17:36:07 -05:00
|
|
|
///
|
2021-07-29 05:16:06 -05:00
|
|
|
/// ### Example
|
2020-10-28 17:36:07 -05:00
|
|
|
/// ```rust
|
|
|
|
/// #[derive(Clone, Copy)]
|
|
|
|
/// struct TooLarge([u8; 2048]);
|
|
|
|
///
|
|
|
|
/// // Bad
|
|
|
|
/// fn foo(v: TooLarge) {}
|
|
|
|
/// ```
|
|
|
|
/// ```rust
|
|
|
|
/// #[derive(Clone, Copy)]
|
|
|
|
/// struct TooLarge([u8; 2048]);
|
|
|
|
///
|
|
|
|
/// // Good
|
|
|
|
/// fn foo(v: &TooLarge) {}
|
|
|
|
/// ```
|
Added `clippy::version` attribute to all normal lints
So, some context for this, well, more a story. I'm not used to scripting, I've never really scripted anything, even if it's a valuable skill. I just never really needed it. Now, `@flip1995` correctly suggested using a script for this in `rust-clippy#7813`...
And I decided to write a script using nushell because why not? This was a mistake... I spend way more time on this than I would like to admit. It has definitely been more than 4 hours. It shouldn't take that long, but me being new to scripting and nushell just wasn't a good mixture... Anyway, here is the script that creates another script which adds the versions. Fun...
Just execute this on the `gh-pages` branch and the resulting `replacer.sh` in `clippy_lints` and it should all work.
```nu
mv v0.0.212 rust-1.00.0;
mv beta rust-1.57.0;
mv master rust-1.58.0;
let paths = (open ./rust-1.58.0/lints.json | select id id_span | flatten | select id path);
let versions = (
ls | where name =~ "rust-" | select name | format {name}/lints.json |
each { open $it | select id | insert version $it | str substring "5,11" version} |
group-by id | rotate counter-clockwise id version |
update version {get version | first 1} | flatten | select id version);
$paths | each { |row|
let version = ($versions | where id == ($row.id) | format {version})
let idu = ($row.id | str upcase)
$"sed -i '0,/($idu),/{s/pub ($idu),/#[clippy::version = "($version)"]\n pub ($idu),/}' ($row.path)"
} | str collect ";" | str find-replace --all '1.00.0' 'pre 1.29.0' | save "replacer.sh";
```
And this still has some problems, but at this point I just want to be done -.-
2021-10-21 14:06:26 -05:00
|
|
|
#[clippy::version = "1.49.0"]
|
2020-10-28 17:36:07 -05:00
|
|
|
pub LARGE_TYPES_PASSED_BY_VALUE,
|
|
|
|
pedantic,
|
|
|
|
"functions taking large arguments by value"
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Copy, Clone)]
|
|
|
|
pub struct PassByRefOrValue {
|
|
|
|
ref_min_size: u64,
|
|
|
|
value_max_size: u64,
|
2021-06-03 01:41:37 -05:00
|
|
|
avoid_breaking_exported_api: bool,
|
2020-10-28 17:36:07 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'tcx> PassByRefOrValue {
|
2021-06-03 01:41:37 -05:00
|
|
|
pub fn new(
|
|
|
|
ref_min_size: Option<u64>,
|
|
|
|
value_max_size: u64,
|
|
|
|
avoid_breaking_exported_api: bool,
|
|
|
|
target: &Target,
|
|
|
|
) -> Self {
|
2020-10-28 17:36:07 -05:00
|
|
|
let ref_min_size = ref_min_size.unwrap_or_else(|| {
|
|
|
|
let bit_width = u64::from(target.pointer_width);
|
|
|
|
// Cap the calculated bit width at 32-bits to reduce
|
|
|
|
// portability problems between 32 and 64-bit targets
|
|
|
|
let bit_width = cmp::min(bit_width, 32);
|
|
|
|
#[allow(clippy::integer_division)]
|
|
|
|
let byte_width = bit_width / 8;
|
|
|
|
// Use a limit of 2 times the register byte width
|
|
|
|
byte_width * 2
|
|
|
|
});
|
|
|
|
|
|
|
|
Self {
|
|
|
|
ref_min_size,
|
|
|
|
value_max_size,
|
2021-06-03 01:41:37 -05:00
|
|
|
avoid_breaking_exported_api,
|
2020-10-28 17:36:07 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-28 17:07:32 -05:00
|
|
|
fn check_poly_fn(&mut self, cx: &LateContext<'tcx>, def_id: LocalDefId, decl: &FnDecl<'_>, span: Option<Span>) {
|
|
|
|
if self.avoid_breaking_exported_api && cx.access_levels.is_exported(def_id) {
|
2021-06-03 01:41:37 -05:00
|
|
|
return;
|
|
|
|
}
|
2020-10-28 17:36:07 -05:00
|
|
|
|
2021-07-28 17:07:32 -05:00
|
|
|
let fn_sig = cx.tcx.fn_sig(def_id);
|
2020-10-23 19:21:27 -05:00
|
|
|
let fn_sig = cx.tcx.erase_late_bound_regions(fn_sig);
|
2020-10-28 17:36:07 -05:00
|
|
|
|
|
|
|
let fn_body = cx.enclosing_body.map(|id| cx.tcx.hir().body(id));
|
|
|
|
|
2021-03-08 17:57:44 -06:00
|
|
|
for (index, (input, &ty)) in iter::zip(decl.inputs, fn_sig.inputs()).enumerate() {
|
2020-10-28 17:36:07 -05:00
|
|
|
// All spans generated from a proc-macro invocation are the same...
|
|
|
|
match span {
|
|
|
|
Some(s) if s == input.span => return,
|
|
|
|
_ => (),
|
|
|
|
}
|
|
|
|
|
|
|
|
match ty.kind() {
|
|
|
|
ty::Ref(input_lt, ty, Mutability::Not) => {
|
|
|
|
// Use lifetimes to determine if we're returning a reference to the
|
|
|
|
// argument. In that case we can't switch to pass-by-value as the
|
|
|
|
// argument will not live long enough.
|
|
|
|
let output_lts = match *fn_sig.output().kind() {
|
|
|
|
ty::Ref(output_lt, _, _) => vec![output_lt],
|
|
|
|
ty::Adt(_, substs) => substs.regions().collect(),
|
|
|
|
_ => vec![],
|
|
|
|
};
|
|
|
|
|
|
|
|
if_chain! {
|
2021-04-08 10:50:13 -05:00
|
|
|
if !output_lts.contains(input_lt);
|
2020-10-28 17:36:07 -05:00
|
|
|
if is_copy(cx, ty);
|
|
|
|
if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
|
|
|
|
if size <= self.ref_min_size;
|
2021-04-08 10:50:13 -05:00
|
|
|
if let hir::TyKind::Rptr(_, MutTy { ty: decl_ty, .. }) = input.kind;
|
2020-10-28 17:36:07 -05:00
|
|
|
then {
|
2021-08-12 04:16:25 -05:00
|
|
|
let value_type = if fn_body.and_then(|body| body.params.get(index)).map_or(false, is_self) {
|
2020-10-28 17:36:07 -05:00
|
|
|
"self".into()
|
|
|
|
} else {
|
|
|
|
snippet(cx, decl_ty.span, "_").into()
|
|
|
|
};
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
TRIVIALLY_COPY_PASS_BY_REF,
|
|
|
|
input.span,
|
|
|
|
&format!("this argument ({} byte) is passed by reference, but would be more efficient if passed by value (limit: {} byte)", size, self.ref_min_size),
|
|
|
|
"consider passing by value instead",
|
|
|
|
value_type,
|
|
|
|
Applicability::Unspecified,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
ty::Adt(_, _) | ty::Array(_, _) | ty::Tuple(_) => {
|
|
|
|
// if function has a body and parameter is annotated with mut, ignore
|
|
|
|
if let Some(param) = fn_body.and_then(|body| body.params.get(index)) {
|
|
|
|
match param.pat.kind {
|
|
|
|
PatKind::Binding(BindingAnnotation::Unannotated, _, _, _) => {},
|
|
|
|
_ => continue,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if_chain! {
|
|
|
|
if is_copy(cx, ty);
|
|
|
|
if !is_self_ty(input);
|
|
|
|
if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes());
|
|
|
|
if size > self.value_max_size;
|
|
|
|
then {
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
LARGE_TYPES_PASSED_BY_VALUE,
|
|
|
|
input.span,
|
|
|
|
&format!("this argument ({} byte) is passed by value, but might be more efficient if passed by reference (limit: {} byte)", size, self.value_max_size),
|
|
|
|
"consider passing by reference instead",
|
|
|
|
format!("&{}", snippet(cx, input.span, "_")),
|
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
_ => {},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl_lint_pass!(PassByRefOrValue => [TRIVIALLY_COPY_PASS_BY_REF, LARGE_TYPES_PASSED_BY_VALUE]);
|
|
|
|
|
|
|
|
impl<'tcx> LateLintPass<'tcx> for PassByRefOrValue {
|
|
|
|
fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
|
|
|
|
if item.span.from_expansion() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let hir::TraitItemKind::Fn(method_sig, _) = &item.kind {
|
2021-07-28 17:07:32 -05:00
|
|
|
self.check_poly_fn(cx, item.def_id, &*method_sig.decl, None);
|
2020-10-28 17:36:07 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_fn(
|
|
|
|
&mut self,
|
|
|
|
cx: &LateContext<'tcx>,
|
|
|
|
kind: FnKind<'tcx>,
|
|
|
|
decl: &'tcx FnDecl<'_>,
|
|
|
|
_body: &'tcx Body<'_>,
|
|
|
|
span: Span,
|
|
|
|
hir_id: HirId,
|
|
|
|
) {
|
|
|
|
if span.from_expansion() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
match kind {
|
2020-11-27 02:24:42 -06:00
|
|
|
FnKind::ItemFn(.., header, _) => {
|
2020-10-28 17:36:07 -05:00
|
|
|
if header.abi != Abi::Rust {
|
|
|
|
return;
|
|
|
|
}
|
2020-11-27 02:24:42 -06:00
|
|
|
let attrs = cx.tcx.hir().attrs(hir_id);
|
2020-10-28 17:36:07 -05:00
|
|
|
for a in attrs {
|
|
|
|
if let Some(meta_items) = a.meta_item_list() {
|
2020-11-05 07:29:48 -06:00
|
|
|
if a.has_name(sym::proc_macro_derive)
|
|
|
|
|| (a.has_name(sym::inline) && attr::list_contains_name(&meta_items, sym::always))
|
2020-10-28 17:36:07 -05:00
|
|
|
{
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
FnKind::Method(..) => (),
|
2020-11-27 02:24:42 -06:00
|
|
|
FnKind::Closure => return,
|
2020-10-28 17:36:07 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// Exclude non-inherent impls
|
|
|
|
if let Some(Node::Item(item)) = cx.tcx.hir().find(cx.tcx.hir().get_parent_node(hir_id)) {
|
2020-12-20 10:19:49 -06:00
|
|
|
if matches!(
|
|
|
|
item.kind,
|
2020-11-22 16:46:21 -06:00
|
|
|
ItemKind::Impl(Impl { of_trait: Some(_), .. }) | ItemKind::Trait(..)
|
2020-12-20 10:19:49 -06:00
|
|
|
) {
|
2020-10-28 17:36:07 -05:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-07-28 17:07:32 -05:00
|
|
|
self.check_poly_fn(cx, cx.tcx.hir().local_def_id(hir_id), decl, Some(span));
|
2020-10-28 17:36:07 -05:00
|
|
|
}
|
|
|
|
}
|