blob: 6f6b5166f76438f3f733d733affff0a89f0292d8 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/**
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//------------------------------------------------------------------------------
8// Requirements
9//------------------------------------------------------------------------------
10
11const astUtils = require("./utils/ast-utils");
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010012const keywords = require("./utils/keywords");
Yang Guo4fd355c2019-09-19 10:59:03 +020013
14//------------------------------------------------------------------------------
15// Rule Definition
16//------------------------------------------------------------------------------
17
18const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u;
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +010019
20// `null` literal must be handled separately.
21const literalTypesToCheck = new Set(["string", "boolean"]);
Yang Guo4fd355c2019-09-19 10:59:03 +020022
Tim van der Lippe0ceb4652022-01-06 14:23:36 +010023/** @type {import('../shared/types').Rule} */
Yang Guo4fd355c2019-09-19 10:59:03 +020024module.exports = {
25 meta: {
26 type: "suggestion",
27
28 docs: {
29 description: "enforce dot notation whenever possible",
Yang Guo4fd355c2019-09-19 10:59:03 +020030 recommended: false,
31 url: "https://eslint.org/docs/rules/dot-notation"
32 },
33
34 schema: [
35 {
36 type: "object",
37 properties: {
38 allowKeywords: {
39 type: "boolean",
40 default: true
41 },
42 allowPattern: {
43 type: "string",
44 default: ""
45 }
46 },
47 additionalProperties: false
48 }
49 ],
50
51 fixable: "code",
52
53 messages: {
54 useDot: "[{{key}}] is better written in dot notation.",
55 useBrackets: ".{{key}} is a syntax error."
56 }
57 },
58
59 create(context) {
60 const options = context.options[0] || {};
61 const allowKeywords = options.allowKeywords === void 0 || options.allowKeywords;
62 const sourceCode = context.getSourceCode();
63
64 let allowPattern;
65
66 if (options.allowPattern) {
67 allowPattern = new RegExp(options.allowPattern, "u");
68 }
69
70 /**
71 * Check if the property is valid dot notation
72 * @param {ASTNode} node The dot notation node
73 * @param {string} value Value which is to be checked
74 * @returns {void}
75 */
76 function checkComputedProperty(node, value) {
77 if (
78 validIdentifier.test(value) &&
79 (allowKeywords || keywords.indexOf(String(value)) === -1) &&
80 !(allowPattern && allowPattern.test(value))
81 ) {
82 const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``;
83
84 context.report({
85 node: node.property,
86 messageId: "useDot",
87 data: {
88 key: formattedValue
89 },
Tim van der Lippe16aca392020-11-13 11:37:13 +000090 *fix(fixer) {
Yang Guo4fd355c2019-09-19 10:59:03 +020091 const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
92 const rightBracket = sourceCode.getLastToken(node);
Tim van der Lippe16aca392020-11-13 11:37:13 +000093 const nextToken = sourceCode.getTokenAfter(node);
Yang Guo4fd355c2019-09-19 10:59:03 +020094
Tim van der Lippe16aca392020-11-13 11:37:13 +000095 // Don't perform any fixes if there are comments inside the brackets.
96 if (sourceCode.commentsExistBetween(leftBracket, rightBracket)) {
Tim van der Lippe2c891972021-07-29 16:22:50 +010097 return;
Yang Guo4fd355c2019-09-19 10:59:03 +020098 }
99
Tim van der Lippe16aca392020-11-13 11:37:13 +0000100 // Replace the brackets by an identifier.
101 if (!node.optional) {
102 yield fixer.insertTextBefore(
103 leftBracket,
104 astUtils.isDecimalInteger(node.object) ? " ." : "."
105 );
106 }
107 yield fixer.replaceTextRange(
Yang Guo4fd355c2019-09-19 10:59:03 +0200108 [leftBracket.range[0], rightBracket.range[1]],
Tim van der Lippe16aca392020-11-13 11:37:13 +0000109 value
Yang Guo4fd355c2019-09-19 10:59:03 +0200110 );
Tim van der Lippe16aca392020-11-13 11:37:13 +0000111
112 // Insert a space after the property if it will be connected to the next token.
113 if (
114 nextToken &&
115 rightBracket.range[1] === nextToken.range[0] &&
116 !astUtils.canTokensBeAdjacent(String(value), nextToken)
117 ) {
118 yield fixer.insertTextAfter(node, " ");
119 }
Yang Guo4fd355c2019-09-19 10:59:03 +0200120 }
121 });
122 }
123 }
124
125 return {
126 MemberExpression(node) {
127 if (
128 node.computed &&
Tim van der Lippec8f6ffd2020-04-06 13:42:00 +0100129 node.property.type === "Literal" &&
130 (literalTypesToCheck.has(typeof node.property.value) || astUtils.isNullLiteral(node.property))
Yang Guo4fd355c2019-09-19 10:59:03 +0200131 ) {
132 checkComputedProperty(node, node.property.value);
133 }
134 if (
135 node.computed &&
136 node.property.type === "TemplateLiteral" &&
137 node.property.expressions.length === 0
138 ) {
139 checkComputedProperty(node, node.property.quasis[0].value.cooked);
140 }
141 if (
142 !allowKeywords &&
143 !node.computed &&
Tim van der Lippe0fb47802021-11-08 16:23:10 +0000144 node.property.type === "Identifier" &&
Yang Guo4fd355c2019-09-19 10:59:03 +0200145 keywords.indexOf(String(node.property.name)) !== -1
146 ) {
147 context.report({
148 node: node.property,
149 messageId: "useBrackets",
150 data: {
151 key: node.property.name
152 },
Tim van der Lippe16aca392020-11-13 11:37:13 +0000153 *fix(fixer) {
154 const dotToken = sourceCode.getTokenBefore(node.property);
Yang Guo4fd355c2019-09-19 10:59:03 +0200155
Tim van der Lippe16aca392020-11-13 11:37:13 +0000156 // A statement that starts with `let[` is parsed as a destructuring variable declaration, not a MemberExpression.
157 if (node.object.type === "Identifier" && node.object.name === "let" && !node.optional) {
Tim van der Lippe2c891972021-07-29 16:22:50 +0100158 return;
Yang Guo4fd355c2019-09-19 10:59:03 +0200159 }
160
Tim van der Lippe16aca392020-11-13 11:37:13 +0000161 // Don't perform any fixes if there are comments between the dot and the property name.
162 if (sourceCode.commentsExistBetween(dotToken, node.property)) {
Tim van der Lippe2c891972021-07-29 16:22:50 +0100163 return;
Yang Guo4fd355c2019-09-19 10:59:03 +0200164 }
165
Tim van der Lippe16aca392020-11-13 11:37:13 +0000166 // Replace the identifier to brackets.
167 if (!node.optional) {
168 yield fixer.remove(dotToken);
169 }
170 yield fixer.replaceText(node.property, `["${node.property.name}"]`);
Yang Guo4fd355c2019-09-19 10:59:03 +0200171 }
172 });
173 }
174 }
175 };
176 }
177};