dot-notation.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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("../util/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u;
  14. const keywords = require("../util/keywords");
  15. module.exports = {
  16. meta: {
  17. type: "suggestion",
  18. docs: {
  19. description: "enforce dot notation whenever possible",
  20. category: "Best Practices",
  21. recommended: false,
  22. url: "https://eslint.org/docs/rules/dot-notation"
  23. },
  24. schema: [
  25. {
  26. type: "object",
  27. properties: {
  28. allowKeywords: {
  29. type: "boolean",
  30. default: true
  31. },
  32. allowPattern: {
  33. type: "string",
  34. default: ""
  35. }
  36. },
  37. additionalProperties: false
  38. }
  39. ],
  40. fixable: "code",
  41. messages: {
  42. useDot: "[{{key}}] is better written in dot notation.",
  43. useBrackets: ".{{key}} is a syntax error."
  44. }
  45. },
  46. create(context) {
  47. const options = context.options[0] || {};
  48. const allowKeywords = options.allowKeywords === void 0 || options.allowKeywords;
  49. const sourceCode = context.getSourceCode();
  50. let allowPattern;
  51. if (options.allowPattern) {
  52. allowPattern = new RegExp(options.allowPattern); // eslint-disable-line require-unicode-regexp
  53. }
  54. /**
  55. * Check if the property is valid dot notation
  56. * @param {ASTNode} node The dot notation node
  57. * @param {string} value Value which is to be checked
  58. * @returns {void}
  59. */
  60. function checkComputedProperty(node, value) {
  61. if (
  62. validIdentifier.test(value) &&
  63. (allowKeywords || keywords.indexOf(String(value)) === -1) &&
  64. !(allowPattern && allowPattern.test(value))
  65. ) {
  66. const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``;
  67. context.report({
  68. node: node.property,
  69. messageId: "useDot",
  70. data: {
  71. key: formattedValue
  72. },
  73. fix(fixer) {
  74. const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
  75. const rightBracket = sourceCode.getLastToken(node);
  76. if (sourceCode.getFirstTokenBetween(leftBracket, rightBracket, { includeComments: true, filter: astUtils.isCommentToken })) {
  77. // Don't perform any fixes if there are comments inside the brackets.
  78. return null;
  79. }
  80. const tokenAfterProperty = sourceCode.getTokenAfter(rightBracket);
  81. const needsSpaceAfterProperty = tokenAfterProperty &&
  82. rightBracket.range[1] === tokenAfterProperty.range[0] &&
  83. !astUtils.canTokensBeAdjacent(String(value), tokenAfterProperty);
  84. const textBeforeDot = astUtils.isDecimalInteger(node.object) ? " " : "";
  85. const textAfterProperty = needsSpaceAfterProperty ? " " : "";
  86. return fixer.replaceTextRange(
  87. [leftBracket.range[0], rightBracket.range[1]],
  88. `${textBeforeDot}.${value}${textAfterProperty}`
  89. );
  90. }
  91. });
  92. }
  93. }
  94. return {
  95. MemberExpression(node) {
  96. if (
  97. node.computed &&
  98. node.property.type === "Literal"
  99. ) {
  100. checkComputedProperty(node, node.property.value);
  101. }
  102. if (
  103. node.computed &&
  104. node.property.type === "TemplateLiteral" &&
  105. node.property.expressions.length === 0
  106. ) {
  107. checkComputedProperty(node, node.property.quasis[0].value.cooked);
  108. }
  109. if (
  110. !allowKeywords &&
  111. !node.computed &&
  112. keywords.indexOf(String(node.property.name)) !== -1
  113. ) {
  114. context.report({
  115. node: node.property,
  116. messageId: "useBrackets",
  117. data: {
  118. key: node.property.name
  119. },
  120. fix(fixer) {
  121. const dot = sourceCode.getTokenBefore(node.property);
  122. const textAfterDot = sourceCode.text.slice(dot.range[1], node.property.range[0]);
  123. if (textAfterDot.trim()) {
  124. // Don't perform any fixes if there are comments between the dot and the property name.
  125. return null;
  126. }
  127. if (node.object.type === "Identifier" && node.object.name === "let") {
  128. /*
  129. * A statement that starts with `let[` is parsed as a destructuring variable declaration, not
  130. * a MemberExpression.
  131. */
  132. return null;
  133. }
  134. return fixer.replaceTextRange(
  135. [dot.range[0], node.property.range[1]],
  136. `[${textAfterDot}"${node.property.name}"]`
  137. );
  138. }
  139. });
  140. }
  141. }
  142. };
  143. }
  144. };