]> git.proxmox.com Git - pve-eslint.git/blob - eslint/lib/rules/no-useless-computed-key.js
import 8.3.0 source
[pve-eslint.git] / eslint / lib / rules / no-useless-computed-key.js
1 /**
2 * @fileoverview Rule to disallow unnecessary computed property keys in object literals
3 * @author Burak Yigit Kaya
4 */
5 "use strict";
6
7 //------------------------------------------------------------------------------
8 // Requirements
9 //------------------------------------------------------------------------------
10
11 const astUtils = require("./utils/ast-utils");
12
13 //------------------------------------------------------------------------------
14 // Helpers
15 //------------------------------------------------------------------------------
16
17 /**
18 * Determines whether the computed key syntax is unnecessarily used for the given node.
19 * In particular, it determines whether removing the square brackets and using the content between them
20 * directly as the key (e.g. ['foo'] -> 'foo') would produce valid syntax and preserve the same behavior.
21 * Valid non-computed keys are only: identifiers, number literals and string literals.
22 * Only literals can preserve the same behavior, with a few exceptions for specific node types:
23 * Property
24 * - { ["__proto__"]: foo } defines a property named "__proto__"
25 * { "__proto__": foo } defines object's prototype
26 * PropertyDefinition
27 * - class C { ["constructor"]; } defines an instance field named "constructor"
28 * class C { "constructor"; } produces a parsing error
29 * - class C { static ["constructor"]; } defines a static field named "constructor"
30 * class C { static "constructor"; } produces a parsing error
31 * - class C { static ["prototype"]; } produces a runtime error (doesn't break the whole script)
32 * class C { static "prototype"; } produces a parsing error (breaks the whole script)
33 * MethodDefinition
34 * - class C { ["constructor"]() {} } defines a prototype method named "constructor"
35 * class C { "constructor"() {} } defines the constructor
36 * - class C { static ["prototype"]() {} } produces a runtime error (doesn't break the whole script)
37 * class C { static "prototype"() {} } produces a parsing error (breaks the whole script)
38 * @param {ASTNode} node The node to check. It can be `Property`, `PropertyDefinition` or `MethodDefinition`.
39 * @throws {Error} (Unreachable.)
40 * @returns {void} `true` if the node has useless computed key.
41 */
42 function hasUselessComputedKey(node) {
43 if (!node.computed) {
44 return false;
45 }
46
47 const { key } = node;
48
49 if (key.type !== "Literal") {
50 return false;
51 }
52
53 const { value } = key;
54
55 if (typeof value !== "number" && typeof value !== "string") {
56 return false;
57 }
58
59 switch (node.type) {
60 case "Property":
61 return value !== "__proto__";
62
63 case "PropertyDefinition":
64 if (node.static) {
65 return value !== "constructor" && value !== "prototype";
66 }
67
68 return value !== "constructor";
69
70 case "MethodDefinition":
71 if (node.static) {
72 return value !== "prototype";
73 }
74
75 return value !== "constructor";
76
77 /* istanbul ignore next */
78 default:
79 throw new Error(`Unexpected node type: ${node.type}`);
80 }
81
82 }
83
84 //------------------------------------------------------------------------------
85 // Rule Definition
86 //------------------------------------------------------------------------------
87
88 module.exports = {
89 meta: {
90 type: "suggestion",
91
92 docs: {
93 description: "disallow unnecessary computed property keys in objects and classes",
94 recommended: false,
95 url: "https://eslint.org/docs/rules/no-useless-computed-key"
96 },
97
98 schema: [{
99 type: "object",
100 properties: {
101 enforceForClassMembers: {
102 type: "boolean",
103 default: false
104 }
105 },
106 additionalProperties: false
107 }],
108 fixable: "code",
109
110 messages: {
111 unnecessarilyComputedProperty: "Unnecessarily computed property [{{property}}] found."
112 }
113 },
114 create(context) {
115 const sourceCode = context.getSourceCode();
116 const enforceForClassMembers = context.options[0] && context.options[0].enforceForClassMembers;
117
118 /**
119 * Reports a given node if it violated this rule.
120 * @param {ASTNode} node The node to check.
121 * @returns {void}
122 */
123 function check(node) {
124 if (hasUselessComputedKey(node)) {
125 const { key } = node;
126
127 context.report({
128 node,
129 messageId: "unnecessarilyComputedProperty",
130 data: { property: sourceCode.getText(key) },
131 fix(fixer) {
132 const leftSquareBracket = sourceCode.getTokenBefore(key, astUtils.isOpeningBracketToken);
133 const rightSquareBracket = sourceCode.getTokenAfter(key, astUtils.isClosingBracketToken);
134
135 // If there are comments between the brackets and the property name, don't do a fix.
136 if (sourceCode.commentsExistBetween(leftSquareBracket, rightSquareBracket)) {
137 return null;
138 }
139
140 const tokenBeforeLeftBracket = sourceCode.getTokenBefore(leftSquareBracket);
141
142 // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} })
143 const needsSpaceBeforeKey = tokenBeforeLeftBracket.range[1] === leftSquareBracket.range[0] &&
144 !astUtils.canTokensBeAdjacent(tokenBeforeLeftBracket, sourceCode.getFirstToken(key));
145
146 const replacementKey = (needsSpaceBeforeKey ? " " : "") + key.raw;
147
148 return fixer.replaceTextRange([leftSquareBracket.range[0], rightSquareBracket.range[1]], replacementKey);
149 }
150 });
151 }
152 }
153
154 /**
155 * A no-op function to act as placeholder for checking a node when the `enforceForClassMembers` option is `false`.
156 * @returns {void}
157 * @private
158 */
159 function noop() {}
160
161 return {
162 Property: check,
163 MethodDefinition: enforceForClassMembers ? check : noop,
164 PropertyDefinition: enforceForClassMembers ? check : noop
165 };
166 }
167 };