Skip to content

Commit

Permalink
feat(eslint-plugin): [no-shadow] add shadowed variable location to th…
Browse files Browse the repository at this point in the history
…e error message
  • Loading branch information
bradzacher committed Jun 13, 2022
1 parent 363b624 commit be3d72b
Show file tree
Hide file tree
Showing 4 changed files with 2,050 additions and 2,032 deletions.
50 changes: 44 additions & 6 deletions packages/eslint-plugin/src/rules/no-shadow.ts
Expand Up @@ -12,7 +12,7 @@ import {
} from '@typescript-eslint/scope-manager';
import * as util from '../util';

type MessageIds = 'noShadow';
type MessageIds = 'noShadow' | 'noShadowGlobal';
type Options = [
{
allow?: string[];
Expand Down Expand Up @@ -64,7 +64,9 @@ export default util.createRule<Options, MessageIds>({
},
],
messages: {
noShadow: "'{{name}}' is already declared in the upper scope.",
noShadow:
"'{{name}}' is already declared in the upper scope on line {{shadowedLine}} column {{shadowedColumn}}.",
noShadowGlobal: "'{{name}}' is already a global variable.",
},
},
defaultOptions: [
Expand Down Expand Up @@ -517,6 +519,28 @@ export default util.createRule<Options, MessageIds>({
);
}

/**
* Get declared line and column of a variable.
* @param variable The variable to get.
* @returns The declared line and column of the variable.
*/
function getDeclaredLocation(
variable: TSESLint.Scope.Variable,
): { global: true } | { global: false; line: number; column: number } {
const identifier = variable.identifiers[0];
if (identifier) {
return {
global: false,
line: identifier.loc.start.line,
column: identifier.loc.start.column + 1,
};
} else {
return {
global: true,
};
}
}

/**
* Checks the current context for shadowed variables.
* @param {Scope} scope Fixme
Expand Down Expand Up @@ -595,12 +619,26 @@ export default util.createRule<Options, MessageIds>({
) &&
!(options.hoist !== 'all' && isInTdz(variable, shadowed))
) {
const location = getDeclaredLocation(shadowed);
const report = location.global
? ({
messageId: 'noShadowGlobal',
data: {
name: variable.name,
},
} as const)
: ({
messageId: 'noShadow',
data: {
name: variable.name,
shadowedLine: location.line,
shadowedColumn: location.column,
},
} as const);

context.report({
node: variable.identifiers[0],
messageId: 'noShadow',
data: {
name: variable.name,
},
...report,
});
}
}
Expand Down

0 comments on commit be3d72b

Please sign in to comment.