Skip to content

Commit ce7f061

Browse files
authored
Update: add shadowed variable loc to message in no-shadow (fixes #13646) (#13841)
* Update: show the original identifier place (refs #13646) * Update: show message when the variable is global (refs #13646) * Update: fix code according to review.
1 parent c60e23f commit ce7f061

2 files changed

Lines changed: 279 additions & 59 deletions

File tree

lib/rules/no-shadow.js

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ module.exports = {
4444
],
4545

4646
messages: {
47-
noShadow: "'{{name}}' is already declared in the upper scope."
47+
noShadow: "'{{name}}' is already declared in the upper scope on line {{shadowedLine}} column {{shadowedColumn}}.",
48+
noShadowGlobal: "'{{name}}' is already a global variable."
4849
}
4950
},
5051

@@ -117,6 +118,29 @@ module.exports = {
117118
return def && def.name.range;
118119
}
119120

121+
/**
122+
* Get declared line and column of a variable.
123+
* @param {eslint-scope.Variable} variable The variable to get.
124+
* @returns {Object} The declared line and column of the variable.
125+
*/
126+
function getDeclaredLocation(variable) {
127+
const identifier = variable.identifiers[0];
128+
let obj;
129+
130+
if (identifier) {
131+
obj = {
132+
global: false,
133+
line: identifier.loc.start.line,
134+
column: identifier.loc.start.column + 1
135+
};
136+
} else {
137+
obj = {
138+
global: true
139+
};
140+
}
141+
return obj;
142+
}
143+
120144
/**
121145
* Checks if a variable is in TDZ of scopeVar.
122146
* @param {Object} variable The variable to check.
@@ -165,10 +189,18 @@ module.exports = {
165189
!isOnInitializer(variable, shadowed) &&
166190
!(options.hoist !== "all" && isInTdz(variable, shadowed))
167191
) {
192+
const location = getDeclaredLocation(shadowed);
193+
const messageId = location.global ? "noShadowGlobal" : "noShadow";
194+
const data = { name: variable.name };
195+
196+
if (!location.global) {
197+
data.shadowedLine = location.line;
198+
data.shadowedColumn = location.column;
199+
}
168200
context.report({
169201
node: variable.identifiers[0],
170-
messageId: "noShadow",
171-
data: variable
202+
messageId,
203+
data
172204
});
173205
}
174206
}

0 commit comments

Comments
 (0)