Skip to content

Commit a2c82be

Browse files
committed
fix(linter/block-scoped-var): better diagnostic messages (#11290)
## What This PR Does Updates diagnostics for `eslint/block-scoped-var` to provide better information, particularly better labels
1 parent 4e606a5 commit a2c82be

File tree

2 files changed

+245
-78
lines changed

2 files changed

+245
-78
lines changed

crates/oxc_linter/src/rules/eslint/block_scoped_var.rs

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,25 @@
11
use oxc_ast::{AstKind, ast::VariableDeclarationKind};
22
use oxc_diagnostics::OxcDiagnostic;
33
use oxc_macros::declare_oxc_lint;
4-
use oxc_span::Span;
4+
use oxc_span::{GetSpan, Span};
55

66
use crate::{AstNode, context::LintContext, rule::Rule};
77

8-
fn block_scoped_var_diagnostic(span: Span, name: &str) -> OxcDiagnostic {
8+
fn redeclaration_diagnostic(decl_span: Span, redecl_span: Span, name: &str) -> OxcDiagnostic {
99
OxcDiagnostic::warn(format!("'{name}' is used outside of binding context."))
1010
.with_help(format!("Variable '{name}' is used outside its declaration block. Declare it outside the block or use 'let'/'const'."))
11-
.with_label(span)
11+
.with_labels([
12+
redecl_span.label("it is redeclared here"),
13+
decl_span.label(format!("'{name}' is first declared here")),
14+
])
15+
}
16+
fn use_outside_scope_diagnostic(decl_span: Span, used_span: Span, name: &str) -> OxcDiagnostic {
17+
OxcDiagnostic::warn(format!("'{name}' is used outside of binding context."))
18+
.with_help(format!("Variable '{name}' is used outside its declaration block. Declare it outside the block or use 'let'/'const'."))
19+
.with_labels([
20+
used_span.label(format!("'{name}' is used here")),
21+
decl_span.label("It is declared in a different scope here"),
22+
])
1223
}
1324

1425
#[derive(Debug, Default, Clone)]
@@ -84,7 +95,11 @@ impl Rule for BlockScopedVar {
8495
for redeclaration in ctx.scoping().symbol_redeclarations(symbol_id) {
8596
let re_scope_id = ctx.nodes().get_node(redeclaration.declaration).scope_id();
8697
if !scope_arr.contains(&re_scope_id) && re_scope_id != cur_node_scope_id {
87-
ctx.diagnostic(block_scoped_var_diagnostic(redeclaration.span, name));
98+
ctx.diagnostic(redeclaration_diagnostic(
99+
item.id.span(),
100+
redeclaration.span,
101+
name,
102+
));
88103
}
89104
}
90105
// e.g. "var a = 4; console.log(a);"
@@ -93,7 +108,8 @@ impl Rule for BlockScopedVar {
93108
if !scope_arr.contains(&reference_scope_id)
94109
&& reference_scope_id != cur_node_scope_id
95110
{
96-
ctx.diagnostic(block_scoped_var_diagnostic(
111+
ctx.diagnostic(use_outside_scope_diagnostic(
112+
item.id.span(),
97113
ctx.reference_span(reference),
98114
name,
99115
));

0 commit comments

Comments
 (0)