-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Add default_box_assignments
lint
#14953
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bluebear94
wants to merge
15
commits into
rust-lang:master
Choose a base branch
from
bluebear94:mf/box-assign-default
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
abaeaee
Add `default_box_assignments` lint
bluebear94 8fc6abd
Fix Clippy lint
bluebear94 76086e8
Fix doc test
bluebear94 f6cbcd1
Add test for macro expansion
bluebear94 b9033d6
Use `Sugg` interface for suggestion
bluebear94 6147d37
Simplify `is_box_of_default` and `is_default_call`
bluebear94 785f0b7
Supress `default_box_assignments` lint for late-init locals
bluebear94 2670c50
Revise diagnostic message
bluebear94 0805610
Add lint for `b = Box::new(value)`
bluebear94 9633fb8
Add tests involving generics
bluebear94 dbf4c13
Update description for lint
bluebear94 bdcb4c9
Apply minor style suggestions
bluebear94 6def4c7
Filter out rhs.span.from_expansion() at the start
bluebear94 22eebd7
Filter out LHS from macro expansion
bluebear94 6538301
Fix suggestion for Box::new around macro invocation
bluebear94 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
use clippy_utils::diagnostics::span_lint_and_then; | ||
use clippy_utils::sugg::Sugg; | ||
use clippy_utils::ty::implements_trait; | ||
use clippy_utils::{is_default_equivalent_call, local_is_initialized, path_def_id, path_to_local}; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::{Expr, ExprKind, LangItem, QPath}; | ||
use rustc_lint::{LateContext, LateLintPass}; | ||
use rustc_middle::ty::{self, Ty}; | ||
use rustc_session::declare_lint_pass; | ||
use rustc_span::sym; | ||
|
||
declare_clippy_lint! { | ||
/// ### What it does | ||
/// Detects assignments of `Default::default()` or `Box::new(value)` | ||
/// to a place of type `Box<T>`. | ||
/// | ||
/// ### Why is this bad? | ||
/// This incurs an extra heap allocation compared to assigning the boxed | ||
/// storage. | ||
/// | ||
/// ### Example | ||
/// ```no_run | ||
/// let mut b = Box::new(1u32); | ||
/// b = Default::default(); | ||
/// ``` | ||
/// Use instead: | ||
/// ```no_run | ||
/// let mut b = Box::new(1u32); | ||
/// *b = Default::default(); | ||
/// ``` | ||
#[clippy::version = "1.89.0"] | ||
pub DEFAULT_BOX_ASSIGNMENTS, | ||
perf, | ||
"assigning a newly created box to `Box<T>` is inefficient" | ||
} | ||
declare_lint_pass!(DefaultBoxAssignments => [DEFAULT_BOX_ASSIGNMENTS]); | ||
|
||
impl LateLintPass<'_> for DefaultBoxAssignments { | ||
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) { | ||
if let ExprKind::Assign(lhs, rhs, _) = &expr.kind | ||
&& !lhs.span.from_expansion() | ||
&& !rhs.span.from_expansion() | ||
{ | ||
let lhs_ty = cx.typeck_results().expr_ty(lhs); | ||
|
||
// No diagnostic for late-initialized locals | ||
if let Some(local) = path_to_local(lhs) | ||
&& !local_is_initialized(cx, local) | ||
{ | ||
return; | ||
} | ||
|
||
let Some(inner_ty) = get_box_inner_type(cx, lhs_ty) else { | ||
return; | ||
}; | ||
|
||
if let Some(default_trait_id) = cx.tcx.get_diagnostic_item(sym::Default) | ||
&& implements_trait(cx, inner_ty, default_trait_id, &[]) | ||
&& is_default_call(cx, rhs) | ||
{ | ||
span_lint_and_then( | ||
cx, | ||
DEFAULT_BOX_ASSIGNMENTS, | ||
expr.span, | ||
"creating a new box with default content", | ||
|diag| { | ||
let mut app = Applicability::MachineApplicable; | ||
let suggestion = format!( | ||
"{} = Default::default()", | ||
Sugg::hir_with_applicability(cx, lhs, "_", &mut app).deref() | ||
); | ||
|
||
diag.note("this creates a needless allocation").span_suggestion( | ||
expr.span, | ||
"replace existing content with default instead", | ||
suggestion, | ||
app, | ||
); | ||
}, | ||
); | ||
} | ||
|
||
if inner_ty.is_sized(cx.tcx, cx.typing_env()) | ||
&& let Some(rhs_inner) = get_box_new_payload(cx, rhs) | ||
{ | ||
span_lint_and_then(cx, DEFAULT_BOX_ASSIGNMENTS, expr.span, "creating a new box", |diag| { | ||
let mut app = Applicability::MachineApplicable; | ||
let suggestion = format!( | ||
"{} = {}", | ||
Sugg::hir_with_applicability(cx, lhs, "_", &mut app).deref(), | ||
Sugg::hir_with_context(cx, rhs_inner, expr.span.ctxt(), "_", &mut app), | ||
); | ||
|
||
diag.note("this creates a needless allocation").span_suggestion( | ||
expr.span, | ||
"replace existing content with inner value instead", | ||
suggestion, | ||
app, | ||
); | ||
}); | ||
} | ||
} | ||
} | ||
} | ||
|
||
fn get_box_inner_type<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> { | ||
if let ty::Adt(def, args) = ty.kind() | ||
&& cx.tcx.is_lang_item(def.did(), LangItem::OwnedBox) | ||
{ | ||
Some(args.type_at(0)) | ||
} else { | ||
None | ||
} | ||
} | ||
|
||
fn is_default_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { | ||
matches!(expr.kind, ExprKind::Call(func, _args) if is_default_equivalent_call(cx, func, Some(expr))) | ||
} | ||
|
||
fn get_box_new_payload<'tcx>(cx: &LateContext<'_>, expr: &Expr<'tcx>) -> Option<&'tcx Expr<'tcx>> { | ||
if let ExprKind::Call(box_new, [arg]) = expr.kind | ||
&& let ExprKind::Path(QPath::TypeRelative(ty, seg)) = box_new.kind | ||
&& seg.ident.name == sym::new | ||
&& path_def_id(cx, ty).is_some_and(|id| Some(id) == cx.tcx.lang_items().owned_box()) | ||
{ | ||
Some(arg) | ||
} else { | ||
None | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
#![warn(clippy::default_box_assignments)] | ||
|
||
fn with_default<T: Default>(b: &mut Box<T>) { | ||
*(*b) = T::default(); | ||
//~^ default_box_assignments | ||
} | ||
|
||
fn with_sized<T>(b: &mut Box<T>, t: T) { | ||
*(*b) = t; | ||
//~^ default_box_assignments | ||
} | ||
|
||
fn with_unsized<const N: usize>(b: &mut Box<[u32]>) { | ||
// No lint for assigning to Box<T> where T: !Default | ||
*b = Box::new([42; N]); | ||
} | ||
|
||
macro_rules! create_default { | ||
() => { | ||
Default::default() | ||
}; | ||
} | ||
|
||
macro_rules! create_zero_box { | ||
() => { | ||
Box::new(0) | ||
}; | ||
} | ||
|
||
macro_rules! same { | ||
($v:ident) => { | ||
$v | ||
}; | ||
} | ||
|
||
macro_rules! mac { | ||
(three) => { | ||
3u32 | ||
}; | ||
} | ||
|
||
fn main() { | ||
let mut b = Box::new(1u32); | ||
*b = Default::default(); | ||
//~^ default_box_assignments | ||
*b = Default::default(); | ||
//~^ default_box_assignments | ||
|
||
// No lint for assigning to the storage | ||
*b = Default::default(); | ||
*b = u32::default(); | ||
|
||
// No lint if either LHS or RHS originates in macro | ||
b = create_default!(); | ||
b = create_zero_box!(); | ||
same!(b) = Default::default(); | ||
|
||
*b = 5; | ||
//~^ default_box_assignments | ||
|
||
*b = mac!(three); | ||
//~^ default_box_assignments | ||
|
||
// No lint for assigning to Box<T> where T: !Default | ||
let mut b = Box::<str>::from("hi".to_string()); | ||
b = Default::default(); | ||
|
||
// No lint for late initializations | ||
#[allow(clippy::needless_late_init)] | ||
let bb: Box<u32>; | ||
bb = Default::default(); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
#![warn(clippy::default_box_assignments)] | ||
|
||
fn with_default<T: Default>(b: &mut Box<T>) { | ||
*b = Box::new(T::default()); | ||
//~^ default_box_assignments | ||
} | ||
|
||
fn with_sized<T>(b: &mut Box<T>, t: T) { | ||
*b = Box::new(t); | ||
//~^ default_box_assignments | ||
} | ||
|
||
fn with_unsized<const N: usize>(b: &mut Box<[u32]>) { | ||
// No lint for assigning to Box<T> where T: !Default | ||
*b = Box::new([42; N]); | ||
} | ||
|
||
macro_rules! create_default { | ||
() => { | ||
Default::default() | ||
}; | ||
} | ||
|
||
macro_rules! create_zero_box { | ||
() => { | ||
Box::new(0) | ||
}; | ||
} | ||
|
||
macro_rules! same { | ||
($v:ident) => { | ||
$v | ||
}; | ||
} | ||
|
||
macro_rules! mac { | ||
(three) => { | ||
3u32 | ||
}; | ||
} | ||
|
||
fn main() { | ||
let mut b = Box::new(1u32); | ||
b = Default::default(); | ||
//~^ default_box_assignments | ||
b = Box::default(); | ||
//~^ default_box_assignments | ||
|
||
// No lint for assigning to the storage | ||
*b = Default::default(); | ||
*b = u32::default(); | ||
|
||
// No lint if either LHS or RHS originates in macro | ||
b = create_default!(); | ||
b = create_zero_box!(); | ||
same!(b) = Default::default(); | ||
|
||
b = Box::new(5); | ||
//~^ default_box_assignments | ||
|
||
b = Box::new(mac!(three)); | ||
//~^ default_box_assignments | ||
|
||
// No lint for assigning to Box<T> where T: !Default | ||
let mut b = Box::<str>::from("hi".to_string()); | ||
b = Default::default(); | ||
|
||
// No lint for late initializations | ||
#[allow(clippy::needless_late_init)] | ||
let bb: Box<u32>; | ||
bb = Default::default(); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
error: creating a new box | ||
--> tests/ui/default_box_assignments.rs:4:5 | ||
| | ||
LL | *b = Box::new(T::default()); | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace existing content with inner value instead: `*(*b) = T::default()` | ||
| | ||
= note: this creates a needless allocation | ||
= note: `-D clippy::default-box-assignments` implied by `-D warnings` | ||
= help: to override `-D warnings` add `#[allow(clippy::default_box_assignments)]` | ||
|
||
error: creating a new box | ||
--> tests/ui/default_box_assignments.rs:9:5 | ||
| | ||
LL | *b = Box::new(t); | ||
| ^^^^^^^^^^^^^^^^ help: replace existing content with inner value instead: `*(*b) = t` | ||
| | ||
= note: this creates a needless allocation | ||
|
||
error: creating a new box with default content | ||
--> tests/ui/default_box_assignments.rs:44:5 | ||
| | ||
LL | b = Default::default(); | ||
| ^^^^^^^^^^^^^^^^^^^^^^ help: replace existing content with default instead: `*b = Default::default()` | ||
| | ||
= note: this creates a needless allocation | ||
|
||
error: creating a new box with default content | ||
--> tests/ui/default_box_assignments.rs:46:5 | ||
| | ||
LL | b = Box::default(); | ||
| ^^^^^^^^^^^^^^^^^^ help: replace existing content with default instead: `*b = Default::default()` | ||
| | ||
= note: this creates a needless allocation | ||
|
||
error: creating a new box | ||
--> tests/ui/default_box_assignments.rs:58:5 | ||
| | ||
LL | b = Box::new(5); | ||
| ^^^^^^^^^^^^^^^ help: replace existing content with inner value instead: `*b = 5` | ||
| | ||
= note: this creates a needless allocation | ||
|
||
error: creating a new box | ||
--> tests/ui/default_box_assignments.rs:61:5 | ||
| | ||
LL | b = Box::new(mac!(three)); | ||
| ^^^^^^^^^^^^^^^^^^^^^^^^^ help: replace existing content with inner value instead: `*b = mac!(three)` | ||
| | ||
= note: this creates a needless allocation | ||
|
||
error: aborting due to 6 previous errors | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.