Skip to content

Commit 0faa294

Browse files
committed
Use the text range for the name. Not the entire syntax in Unused Variable Diagnostic.
1 parent 2e7059c commit 0faa294

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

crates/ide-diagnostics/src/handlers/unused_variables.rs

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use ide_db::{
66
source_change::SourceChange,
77
RootDatabase,
88
};
9+
use syntax::TextRange;
910
use text_edit::TextEdit;
1011

1112
use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext};
@@ -23,6 +24,13 @@ pub(crate) fn unused_variables(
2324
return None;
2425
}
2526
let diagnostic_range = ctx.sema.diagnostics_display_range(ast);
27+
// The range for the Actual Name. We don't want to replace the entire declarition. Using the diagnostic range causes issues within in Array Destructuring.
28+
let name_range =
29+
d.local.primary_source(ctx.sema.db).name().map(|v| v.syntax().value.text_range())?;
30+
// Make sure we are within the diagnostic range for the variable
31+
if !diagnostic_range.range.contains_range(name_range) {
32+
return None;
33+
}
2634
let var_name = d.local.name(ctx.sema.db);
2735
Some(
2836
Diagnostic::new_with_syntax_node_ptr(
@@ -31,20 +39,28 @@ pub(crate) fn unused_variables(
3139
"unused variable",
3240
ast,
3341
)
34-
.with_fixes(fixes(ctx.sema.db, var_name, diagnostic_range, ast.file_id.is_macro()))
42+
.with_fixes(fixes(
43+
ctx.sema.db,
44+
var_name,
45+
name_range,
46+
diagnostic_range,
47+
ast.file_id.is_macro(),
48+
))
3549
.experimental(),
3650
)
3751
}
3852

3953
fn fixes(
4054
db: &RootDatabase,
4155
var_name: Name,
56+
name_range: TextRange,
4257
diagnostic_range: FileRange,
4358
is_in_marco: bool,
4459
) -> Option<Vec<Assist>> {
4560
if is_in_marco {
4661
return None;
4762
}
63+
4864
Some(vec![Assist {
4965
id: AssistId("unscore_unused_variable_name", AssistKind::QuickFix),
5066
label: Label::new(format!(
@@ -56,7 +72,7 @@ fn fixes(
5672
target: diagnostic_range.range,
5773
source_change: Some(SourceChange::from_text_edit(
5874
diagnostic_range.file_id,
59-
TextEdit::replace(diagnostic_range.range, format!("_{}", var_name.display(db))),
75+
TextEdit::replace(name_range, format!("_{}", var_name.display(db))),
6076
)),
6177
trigger_signature_help: false,
6278
}])
@@ -221,6 +237,23 @@ macro_rules! my_macro {
221237
fn main() {
222238
my_macro!();
223239
}
240+
"#,
241+
);
242+
}
243+
#[test]
244+
fn unused_variable_in_array_destructure() {
245+
check_fix(
246+
r#"
247+
fn main() {
248+
let arr = [1, 2, 3, 4, 5];
249+
let [_x, y$0 @ ..] = arr;
250+
}
251+
"#,
252+
r#"
253+
fn main() {
254+
let arr = [1, 2, 3, 4, 5];
255+
let [_x, _y @ ..] = arr;
256+
}
224257
"#,
225258
);
226259
}

0 commit comments

Comments
 (0)