Skip to content

Commit

Permalink
tools: fix bug in prefer-primordials ESLint rule
Browse files Browse the repository at this point in the history
Refs: #40622
  • Loading branch information
aduh95 committed Oct 27, 2021
1 parent e55ab89 commit 899670a
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
32 changes: 32 additions & 0 deletions test/parallel/test-eslint-prefer-primordials.js
Expand Up @@ -158,6 +158,16 @@ new RuleTester({
options: [{ name: 'Reflect' }],
errors: [{ message: /const { ReflectOwnKeys } = primordials/ }]
},
{
code: `
const { Reflect } = primordials;
module.exports = function() {
const { ownKeys } = Reflect;
}
`,
options: [{ name: 'Reflect' }],
errors: [{ message: /const { ReflectOwnKeys } = primordials/ }]
},
{
code: 'new Map()',
options: [{ name: 'Map', into: 'Safe' }],
Expand All @@ -171,5 +181,27 @@ new RuleTester({
options: [{ name: 'Function' }],
errors: [{ message: /const { FunctionPrototype } = primordials/ }]
},
{
code: `
const obj = { Function };
`,
options: [{ name: 'Function' }],
errors: [{ message: /const { Function } = primordials/ }]
},
{
code: `
const rename = Function;
`,
options: [{ name: 'Function' }],
errors: [{ message: /const { Function } = primordials/ }]
},
{
code: `
const rename = Function;
const obj = { rename };
`,
options: [{ name: 'Function' }],
errors: [{ message: /const { Function } = primordials/ }]
},
]
});
23 changes: 19 additions & 4 deletions tools/eslint-rules/prefer-primordials.js
Expand Up @@ -54,7 +54,7 @@ function getDestructuringAssignmentParent(scope, node) {
) {
return null;
}
return declaration.defs[0].node.init.name;
return declaration.defs[0].node.init;
}

const identifierSelector =
Expand Down Expand Up @@ -94,17 +94,19 @@ module.exports = {
return;
}
const name = node.name;
const parentName = getDestructuringAssignmentParent(
const parent = getDestructuringAssignmentParent(
context.getScope(),
node
);
const parentName = parent?.name;
if (!isTarget(nameMap, name) && !isTarget(nameMap, parentName)) {
return;
}

const defs = globalScope.set.get(name)?.defs;
if (parentName && isTarget(nameMap, parentName)) {
if (!defs || defs[0].name.name !== 'primordials') {
if (defs?.[0].name.name !== 'primordials' &&
!reported.has(parent.range[0])) {
reported.add(node.range[0]);
const into = renameMap.get(name);
context.report({
Expand Down Expand Up @@ -147,7 +149,20 @@ module.exports = {
}
});
}
}
},
VariableDeclarator(node) {
const name = node.init?.name;
if (name !== undefined && isTarget(nameMap, name) &&
node.id.type === 'Identifier' &&
!globalScope.set.get(name)?.defs.length) {
reported.add(node.init.range[0]);
context.report({
node,
messageId: 'error',
data: { name },
});
}
},
};
}
};

0 comments on commit 899670a

Please sign in to comment.