no-useless-computed-key.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. return value !== "__proto__";
  53. case "PropertyDefinition":
  54. if (node.static) {
  55. return value !== "constructor" && value !== "prototype";
  56. }
  57. return value !== "constructor";
  58. case "MethodDefinition":
  59. if (node.static) {
  60. return value !== "prototype";
  61. }
  62. return value !== "constructor";
  63. /* c8 ignore next */
  64. default:
  65. throw new Error(`Unexpected node type: ${node.type}`);
  66. }
  67. }
  68. //------------------------------------------------------------------------------
  69. // Rule Definition
  70. //------------------------------------------------------------------------------
  71. /** @type {import('../shared/types').Rule} */
  72. module.exports = {
  73. meta: {
  74. type: "suggestion",
  75. docs: {
  76. description: "Disallow unnecessary computed property keys in objects and classes",
  77. recommended: false,
  78. url: "https://eslint.org/docs/rules/no-useless-computed-key"
  79. },
  80. schema: [{
  81. type: "object",
  82. properties: {
  83. enforceForClassMembers: {
  84. type: "boolean",
  85. default: false
  86. }
  87. },
  88. additionalProperties: false
  89. }],
  90. fixable: "code",
  91. messages: {
  92. unnecessarilyComputedProperty: "Unnecessarily computed property [{{property}}] found."
  93. }
  94. },
  95. create(context) {
  96. const sourceCode = context.getSourceCode();
  97. const enforceForClassMembers = context.options[0] && context.options[0].enforceForClassMembers;
  98. /**
  99. * Reports a given node if it violated this rule.
  100. * @param {ASTNode} node The node to check.
  101. * @returns {void}
  102. */
  103. function check(node) {
  104. if (hasUselessComputedKey(node)) {
  105. const { key } = node;
  106. context.report({
  107. node,
  108. messageId: "unnecessarilyComputedProperty",
  109. data: { property: sourceCode.getText(key) },
  110. fix(fixer) {
  111. const leftSquareBracket = sourceCode.getTokenBefore(key, astUtils.isOpeningBracketToken);
  112. const rightSquareBracket = sourceCode.getTokenAfter(key, astUtils.isClosingBracketToken);
  113. // If there are comments between the brackets and the property name, don't do a fix.
  114. if (sourceCode.commentsExistBetween(leftSquareBracket, rightSquareBracket)) {
  115. return null;
  116. }
  117. const tokenBeforeLeftBracket = sourceCode.getTokenBefore(leftSquareBracket);
  118. // Insert a space before the key to avoid changing identifiers, e.g. ({ get[2]() {} }) to ({ get2() {} })
  119. const needsSpaceBeforeKey = tokenBeforeLeftBracket.range[1] === leftSquareBracket.range[0] &&
  120. !astUtils.canTokensBeAdjacent(tokenBeforeLeftBracket, sourceCode.getFirstToken(key));
  121. const replacementKey = (needsSpaceBeforeKey ? " " : "") + key.raw;
  122. return fixer.replaceTextRange([leftSquareBracket.range[0], rightSquareBracket.range[1]], replacementKey);
  123. }
  124. });
  125. }
  126. }
  127. /**
  128. * A no-op function to act as placeholder for checking a node when the `enforceForClassMembers` option is `false`.
  129. * @returns {void}
  130. * @private
  131. */
  132. function noop() {}
  133. return {
  134. Property: check,
  135. MethodDefinition: enforceForClassMembers ? check : noop,
  136. PropertyDefinition: enforceForClassMembers ? check : noop
  137. };
  138. }
  139. };