dot-notation.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /**
  2. * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible.
  3. * @author Josh Perez
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. const keywords = require("./utils/keywords");
  11. //------------------------------------------------------------------------------
  12. // Rule Definition
  13. //------------------------------------------------------------------------------
  14. const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u;
  15. // `null` literal must be handled separately.
  16. const literalTypesToCheck = new Set(["string", "boolean"]);
  17. /** @type {import('../shared/types').Rule} */
  18. module.exports = {
  19. meta: {
  20. type: "suggestion",
  21. docs: {
  22. description: "Enforce dot notation whenever possible",
  23. recommended: false,
  24. url: "https://eslint.org/docs/rules/dot-notation"
  25. },
  26. schema: [
  27. {
  28. type: "object",
  29. properties: {
  30. allowKeywords: {
  31. type: "boolean",
  32. default: true
  33. },
  34. allowPattern: {
  35. type: "string",
  36. default: ""
  37. }
  38. },
  39. additionalProperties: false
  40. }
  41. ],
  42. fixable: "code",
  43. messages: {
  44. useDot: "[{{key}}] is better written in dot notation.",
  45. useBrackets: ".{{key}} is a syntax error."
  46. }
  47. },
  48. create(context) {
  49. const options = context.options[0] || {};
  50. const allowKeywords = options.allowKeywords === void 0 || options.allowKeywords;
  51. const sourceCode = context.getSourceCode();
  52. let allowPattern;
  53. if (options.allowPattern) {
  54. allowPattern = new RegExp(options.allowPattern, "u");
  55. }
  56. /**
  57. * Check if the property is valid dot notation
  58. * @param {ASTNode} node The dot notation node
  59. * @param {string} value Value which is to be checked
  60. * @returns {void}
  61. */
  62. function checkComputedProperty(node, value) {
  63. if (
  64. validIdentifier.test(value) &&
  65. (allowKeywords || !keywords.includes(String(value))) &&
  66. !(allowPattern && allowPattern.test(value))
  67. ) {
  68. const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``;
  69. context.report({
  70. node: node.property,
  71. messageId: "useDot",
  72. data: {
  73. key: formattedValue
  74. },
  75. *fix(fixer) {
  76. const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
  77. const rightBracket = sourceCode.getLastToken(node);
  78. const nextToken = sourceCode.getTokenAfter(node);
  79. // Don't perform any fixes if there are comments inside the brackets.
  80. if (sourceCode.commentsExistBetween(leftBracket, rightBracket)) {
  81. return;
  82. }
  83. // Replace the brackets by an identifier.
  84. if (!node.optional) {
  85. yield fixer.insertTextBefore(
  86. leftBracket,
  87. astUtils.isDecimalInteger(node.object) ? " ." : "."
  88. );
  89. }
  90. yield fixer.replaceTextRange(
  91. [leftBracket.range[0], rightBracket.range[1]],
  92. value
  93. );
  94. // Insert a space after the property if it will be connected to the next token.
  95. if (
  96. nextToken &&
  97. rightBracket.range[1] === nextToken.range[0] &&
  98. !astUtils.canTokensBeAdjacent(String(value), nextToken)
  99. ) {
  100. yield fixer.insertTextAfter(node, " ");
  101. }
  102. }
  103. });
  104. }
  105. }
  106. return {
  107. MemberExpression(node) {
  108. if (
  109. node.computed &&
  110. node.property.type === "Literal" &&
  111. (literalTypesToCheck.has(typeof node.property.value) || astUtils.isNullLiteral(node.property))
  112. ) {
  113. checkComputedProperty(node, node.property.value);
  114. }
  115. if (
  116. node.computed &&
  117. node.property.type === "TemplateLiteral" &&
  118. node.property.expressions.length === 0
  119. ) {
  120. checkComputedProperty(node, node.property.quasis[0].value.cooked);
  121. }
  122. if (
  123. !allowKeywords &&
  124. !node.computed &&
  125. node.property.type === "Identifier" &&
  126. keywords.includes(String(node.property.name))
  127. ) {
  128. context.report({
  129. node: node.property,
  130. messageId: "useBrackets",
  131. data: {
  132. key: node.property.name
  133. },
  134. *fix(fixer) {
  135. const dotToken = sourceCode.getTokenBefore(node.property);
  136. // A statement that starts with `let[` is parsed as a destructuring variable declaration, not a MemberExpression.
  137. if (node.object.type === "Identifier" && node.object.name === "let" && !node.optional) {
  138. return;
  139. }
  140. // Don't perform any fixes if there are comments between the dot and the property name.
  141. if (sourceCode.commentsExistBetween(dotToken, node.property)) {
  142. return;
  143. }
  144. // Replace the identifier to brackets.
  145. if (!node.optional) {
  146. yield fixer.remove(dotToken);
  147. }
  148. yield fixer.replaceText(node.property, `["${node.property.name}"]`);
  149. }
  150. });
  151. }
  152. }
  153. };
  154. }
  155. };