-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Improve diagnostic for when field is never read #83004
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
Closed
Closed
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5a8bd7d
Tests for field is never read diagnostic
sunjay 9b7d139
Added suggestion and note for when a field is never used
sunjay db3f8e4
Updating test stderr files
sunjay f8e6911
Trying out a new message that works a little better for values *and* …
sunjay 0fb9c23
New shorter diagnostic note that is different for items versus fields
sunjay 33f31eb
Putting help message only under the identifier that needs to be prefixed
sunjay 808f856
Blessing stderr from new UI tests added since last rebase
sunjay 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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,6 +3,7 @@ | |
// from live codes are live, and everything else is dead. | ||
|
||
use rustc_data_structures::fx::{FxHashMap, FxHashSet}; | ||
use rustc_errors::Applicability; | ||
use rustc_hir as hir; | ||
use rustc_hir::def::{CtorOf, DefKind, Res}; | ||
use rustc_hir::def_id::DefId; | ||
|
@@ -15,7 +16,7 @@ use rustc_middle::middle::privacy; | |
use rustc_middle::ty::{self, DefIdTree, TyCtxt}; | ||
use rustc_session::lint; | ||
|
||
use rustc_span::symbol::{sym, Symbol}; | ||
use rustc_span::symbol::{sym, Ident, Symbol}; | ||
|
||
// Any local node that may call something in its body block should be | ||
// explored. For example, if it's a live Node::Item that is a | ||
|
@@ -516,6 +517,13 @@ fn find_live<'tcx>( | |
symbol_visitor.live_symbols | ||
} | ||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
enum ExtraNote { | ||
/// Use this to provide some examples in the diagnostic of potential other purposes for a value | ||
/// or field that is dead code | ||
OtherPurposeExamples, | ||
} | ||
|
||
struct DeadVisitor<'tcx> { | ||
tcx: TyCtxt<'tcx>, | ||
live_symbols: FxHashSet<hir::HirId>, | ||
|
@@ -581,14 +589,42 @@ impl DeadVisitor<'tcx> { | |
&mut self, | ||
id: hir::HirId, | ||
span: rustc_span::Span, | ||
name: Symbol, | ||
name: Ident, | ||
participle: &str, | ||
extra_note: Option<ExtraNote>, | ||
) { | ||
if !name.as_str().starts_with('_') { | ||
self.tcx.struct_span_lint_hir(lint::builtin::DEAD_CODE, id, span, |lint| { | ||
let def_id = self.tcx.hir().local_def_id(id); | ||
let descr = self.tcx.def_kind(def_id).descr(def_id.to_def_id()); | ||
lint.build(&format!("{} is never {}: `{}`", descr, participle, name)).emit() | ||
|
||
let prefixed = vec![(name.span, format!("_{}", name))]; | ||
|
||
let mut diag = | ||
lint.build(&format!("{} is never {}: `{}`", descr, participle, name)); | ||
|
||
diag.multipart_suggestion( | ||
"if this is intentional, prefix it with an underscore", | ||
sunjay marked this conversation as resolved.
Show resolved
Hide resolved
|
||
prefixed, | ||
Applicability::MachineApplicable, | ||
); | ||
|
||
let mut note = format!( | ||
"the leading underscore signals that this {} serves some other \ | ||
purpose even if it isn't used in a way that we can detect.", | ||
descr, | ||
); | ||
if matches!(extra_note, Some(ExtraNote::OtherPurposeExamples)) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be more future proof to use a |
||
note += " (e.g. for its effect when dropped or in foreign code)"; | ||
} | ||
|
||
diag.note(¬e); | ||
|
||
// Force the note we added to the front, before any other subdiagnostics | ||
// added in lint.build(...) | ||
diag.children.rotate_right(1); | ||
sunjay marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
diag.emit() | ||
}); | ||
} | ||
} | ||
|
@@ -634,7 +670,7 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { | |
hir::ItemKind::Struct(..) => "constructed", // Issue #52325 | ||
_ => "used", | ||
}; | ||
self.warn_dead_code(item.hir_id(), span, item.ident.name, participle); | ||
self.warn_dead_code(item.hir_id(), span, item.ident, participle, None); | ||
} else { | ||
// Only continue if we didn't warn | ||
intravisit::walk_item(self, item); | ||
|
@@ -648,22 +684,28 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { | |
id: hir::HirId, | ||
) { | ||
if self.should_warn_about_variant(&variant) { | ||
self.warn_dead_code(variant.id, variant.span, variant.ident.name, "constructed"); | ||
self.warn_dead_code(variant.id, variant.span, variant.ident, "constructed", None); | ||
} else { | ||
intravisit::walk_variant(self, variant, g, id); | ||
} | ||
} | ||
|
||
fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem<'tcx>) { | ||
if self.should_warn_about_foreign_item(fi) { | ||
self.warn_dead_code(fi.hir_id(), fi.span, fi.ident.name, "used"); | ||
self.warn_dead_code(fi.hir_id(), fi.span, fi.ident, "used", None); | ||
} | ||
intravisit::walk_foreign_item(self, fi); | ||
} | ||
|
||
fn visit_field_def(&mut self, field: &'tcx hir::FieldDef<'tcx>) { | ||
if self.should_warn_about_field(&field) { | ||
self.warn_dead_code(field.hir_id, field.span, field.ident.name, "read"); | ||
self.warn_dead_code( | ||
field.hir_id, | ||
field.span, | ||
field.ident, | ||
"read", | ||
Some(ExtraNote::OtherPurposeExamples), | ||
); | ||
} | ||
intravisit::walk_field_def(self, field); | ||
} | ||
|
@@ -675,8 +717,9 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { | |
self.warn_dead_code( | ||
impl_item.hir_id(), | ||
impl_item.span, | ||
impl_item.ident.name, | ||
impl_item.ident, | ||
"used", | ||
None, | ||
); | ||
} | ||
self.visit_nested_body(body_id) | ||
|
@@ -694,7 +737,7 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { | |
} else { | ||
impl_item.ident.span | ||
}; | ||
self.warn_dead_code(impl_item.hir_id(), span, impl_item.ident.name, "used"); | ||
self.warn_dead_code(impl_item.hir_id(), span, impl_item.ident, "used", None); | ||
} | ||
self.visit_nested_body(body_id) | ||
} | ||
|
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
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,42 @@ | ||
//! The field `guard` is never used directly, but it is still useful for its side effect when | ||
//! dropped. Since rustc doesn't consider a `Drop` impl as a use, we want to make sure we at least | ||
//! produce a helpful diagnostic that points the user to what they can do if they indeed intended to | ||
//! have a field that is only used for its `Drop` side effect. | ||
//! | ||
//! Issue: https://github.com/rust-lang/rust/issues/81658 | ||
|
||
#![deny(dead_code)] | ||
|
||
use std::sync::{Mutex, MutexGuard}; | ||
|
||
/// Holds a locked value until it is dropped | ||
pub struct Locked<'a, T> { | ||
// Field is kept for its affect when dropped, but otherwise unused | ||
guard: MutexGuard<'a, T>, //~ ERROR field is never read | ||
} | ||
|
||
impl<'a, T> Locked<'a, T> { | ||
pub fn new(value: &'a Mutex<T>) -> Self { | ||
Self { | ||
guard: value.lock().unwrap(), | ||
} | ||
} | ||
} | ||
|
||
fn main() { | ||
let items = Mutex::new(vec![1, 2, 3]); | ||
|
||
// Hold a lock on items while doing something else | ||
let result = { | ||
// The lock will be released at the end of this scope | ||
let _lock = Locked::new(&items); | ||
|
||
do_something_else() | ||
}; | ||
|
||
println!("{}", result); | ||
} | ||
|
||
fn do_something_else() -> i32 { | ||
1 + 1 | ||
} |
17 changes: 17 additions & 0 deletions
17
src/test/ui/lint/dead-code/drop-only-field-issue-81658.stderr
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,17 @@ | ||
error: field is never read: `guard` | ||
--> $DIR/drop-only-field-issue-81658.rs:15:5 | ||
| | ||
LL | guard: MutexGuard<'a, T>, | ||
| -----^^^^^^^^^^^^^^^^^^^ | ||
| | | ||
| help: if this is intentional, prefix it with an underscore: `_guard` | ||
| | ||
= note: the leading underscore signals that this field serves some other purpose even if it isn't used in a way that we can detect. (e.g. for its effect when dropped or in foreign code) | ||
note: the lint level is defined here | ||
--> $DIR/drop-only-field-issue-81658.rs:8:9 | ||
| | ||
LL | #![deny(dead_code)] | ||
| ^^^^^^^^^ | ||
|
||
error: aborting due to previous error | ||
|
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
50 changes: 50 additions & 0 deletions
50
src/test/ui/lint/dead-code/field-used-in-ffi-issue-81658.rs
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,50 @@ | ||
//! The field `items` is being "used" by FFI (implicitly through pointers). However, since rustc | ||
//! doesn't know how to detect that, we produce a message that says the field is unused. This can | ||
//! cause some confusion and we want to make sure our diagnostics help as much as they can. | ||
//! | ||
//! Issue: https://github.com/rust-lang/rust/issues/81658 | ||
|
||
#![deny(dead_code)] | ||
|
||
/// A struct for holding on to data while it is being used in our FFI code | ||
pub struct FFIData<T> { | ||
/// These values cannot be dropped while the pointers to each item | ||
/// are still in use | ||
items: Option<Vec<T>>, //~ ERROR field is never read | ||
} | ||
|
||
impl<T> FFIData<T> { | ||
pub fn new() -> Self { | ||
Self {items: None} | ||
} | ||
|
||
/// Load items into this type and return pointers to each item that can | ||
/// be passed to FFI | ||
pub fn load(&mut self, items: Vec<T>) -> Vec<*const T> { | ||
let ptrs = items.iter().map(|item| item as *const _).collect(); | ||
|
||
self.items = Some(items); | ||
|
||
ptrs | ||
} | ||
} | ||
|
||
extern { | ||
/// The FFI code that uses items | ||
fn process_item(item: *const i32); | ||
} | ||
|
||
fn main() { | ||
// Data cannot be dropped until the end of this scope or else the items | ||
// will be dropped before they are processed | ||
let mut data = FFIData::new(); | ||
|
||
let ptrs = data.load(vec![1, 2, 3, 4, 5]); | ||
|
||
for ptr in ptrs { | ||
// Safety: This pointer is valid as long as the arena is in scope | ||
unsafe { process_item(ptr); } | ||
} | ||
|
||
// Items will be safely freed at the end of this scope | ||
} |
17 changes: 17 additions & 0 deletions
17
src/test/ui/lint/dead-code/field-used-in-ffi-issue-81658.stderr
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,17 @@ | ||
error: field is never read: `items` | ||
--> $DIR/field-used-in-ffi-issue-81658.rs:13:5 | ||
| | ||
LL | items: Option<Vec<T>>, | ||
| -----^^^^^^^^^^^^^^^^ | ||
| | | ||
| help: if this is intentional, prefix it with an underscore: `_items` | ||
| | ||
= note: the leading underscore signals that this field serves some other purpose even if it isn't used in a way that we can detect. (e.g. for its effect when dropped or in foreign code) | ||
note: the lint level is defined here | ||
--> $DIR/field-used-in-ffi-issue-81658.rs:7:9 | ||
| | ||
LL | #![deny(dead_code)] | ||
| ^^^^^^^^^ | ||
|
||
error: aborting due to previous error | ||
|
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
Oops, something went wrong.
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.