no-new-native-nonconstructor.js
2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* @fileoverview Rule to disallow use of the new operator with global non-constructor functions
* @author Sosuke Suzuki
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const nonConstructorGlobalFunctionNames = ["Symbol", "BigInt"];
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "problem",
docs: {
description: "Disallow `new` operators with global non-constructor functions",
recommended: false,
url: "https://eslint.org/docs/rules/no-new-native-nonconstructor"
},
schema: [],
messages: {
noNewNonconstructor: "`{{name}}` cannot be called as a constructor."
}
},
create(context) {
return {
"Program:exit"() {
const globalScope = context.getScope();
for (const nonConstructorName of nonConstructorGlobalFunctionNames) {
const variable = globalScope.set.get(nonConstructorName);
if (variable && variable.defs.length === 0) {
variable.references.forEach(ref => {
const node = ref.identifier;
const parent = node.parent;
if (parent && parent.type === "NewExpression" && parent.callee === node) {
context.report({
node,
messageId: "noNewNonconstructor",
data: { name: nonConstructorName }
});
}
});
}
}
}
};
}
};