Skip to content

Commit 98167e8

Browse files
aduh95bengl
authored andcommitted
tools: fix bugs in prefer-primordials linter rule
The ESLint rule would repport false positive if code is using an identifier that happens to have the same name as a primordials member. PR-URL: #42010 Reviewed-By: Shingo Inoue <leko.noor@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com>
1 parent 4fbe064 commit 98167e8

2 files changed

Lines changed: 45 additions & 2 deletions

File tree

‎test/parallel/test-eslint-prefer-primordials.js‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,34 @@ new RuleTester({
9999
`,
100100
options: [{name: 'Function'}],
101101
},
102+
{
103+
code: 'function identifier() {}',
104+
options: [{name: 'identifier'}]
105+
},
106+
{
107+
code: 'function* identifier() {}',
108+
options: [{name: 'identifier'}]
109+
},
110+
{
111+
code: 'class identifier {}',
112+
options: [{name: 'identifier'}]
113+
},
114+
{
115+
code: 'new class { identifier(){} }',
116+
options: [{name: 'identifier'}]
117+
},
118+
{
119+
code: 'const a = { identifier: \'4\' }',
120+
options: [{name: 'identifier'}]
121+
},
122+
{
123+
code: 'identifier:{const a = 4}',
124+
options: [{name: 'identifier'}]
125+
},
126+
{
127+
code: 'switch(0){case identifier:}',
128+
options: [{name: 'identifier'}]
129+
},
102130
],
103131
invalid: [
104132
{

‎tools/eslint-rules/prefer-primordials.js‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,18 @@ function getDestructuringAssignmentParent(scope, node) {
5757
returndeclaration.defs[0].node.init;
5858
}
5959

60-
constidentifierSelector=
61-
'[type!=VariableDeclarator][type!=MemberExpression]>Identifier';
60+
constparentSelectors=[
61+
// We want to select identifiers that refer to other references, not the ones
62+
// that create a new reference.
63+
'ClassDeclaration',
64+
'FunctionDeclaration',
65+
'LabeledStatement',
66+
'MemberExpression',
67+
'MethodDefinition',
68+
'SwitchCase',
69+
'VariableDeclarator',
70+
];
71+
constidentifierSelector=parentSelectors.map((selector)=>`[type!=${selector}]`).join('')+'>Identifier';
6272

6373
module.exports={
6474
meta: {
@@ -90,6 +100,11 @@ module.exports = {
90100
reported=newSet();
91101
},
92102
[identifierSelector](node){
103+
if(node.parent.type==='Property'&&node.parent.key===node){
104+
// If the identifier is the key for this property declaration, it
105+
// can't be referring to a primordials member.
106+
return;
107+
}
93108
if(reported.has(node.range[0])){
94109
return;
95110
}

0 commit comments

Comments
 (0)