no-useless-computed-key.js 5.8 KB

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