dot-notation.js 6.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/**
 * @fileoverview Rule to warn about using dot notation instead of square bracket notation when possible.
 * @author Josh Perez
 */
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("./utils/ast-utils");
const keywords = require("./utils/keywords");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

const validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/u;

// `null` literal must be handled separately.
const literalTypesToCheck = new Set(["string", "boolean"]);

module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "enforce dot notation whenever possible",
            category: "Best Practices",
            recommended: false,
            url: "https://eslint.org/docs/rules/dot-notation"
        },

        schema: [
            {
                type: "object",
                properties: {
                    allowKeywords: {
                        type: "boolean",
                        default: true
                    },
                    allowPattern: {
                        type: "string",
                        default: ""
                    }
                },
                additionalProperties: false
            }
        ],

        fixable: "code",

        messages: {
            useDot: "[{{key}}] is better written in dot notation.",
            useBrackets: ".{{key}} is a syntax error."
        }
    },

    create(context) {
        const options = context.options[0] || {};
        const allowKeywords = options.allowKeywords === void 0 || options.allowKeywords;
        const sourceCode = context.getSourceCode();

        let allowPattern;

        if (options.allowPattern) {
            allowPattern = new RegExp(options.allowPattern, "u");
        }

        /**
         * Check if the property is valid dot notation
         * @param {ASTNode} node The dot notation node
         * @param {string} value Value which is to be checked
         * @returns {void}
         */
        function checkComputedProperty(node, value) {
            if (
                validIdentifier.test(value) &&
                (allowKeywords || keywords.indexOf(String(value)) === -1) &&
                !(allowPattern && allowPattern.test(value))
            ) {
                const formattedValue = node.property.type === "Literal" ? JSON.stringify(value) : `\`${value}\``;

                context.report({
                    node: node.property,
                    messageId: "useDot",
                    data: {
                        key: formattedValue
                    },
                    *fix(fixer) {
                        const leftBracket = sourceCode.getTokenAfter(node.object, astUtils.isOpeningBracketToken);
                        const rightBracket = sourceCode.getLastToken(node);
                        const nextToken = sourceCode.getTokenAfter(node);

                        // Don't perform any fixes if there are comments inside the brackets.
                        if (sourceCode.commentsExistBetween(leftBracket, rightBracket)) {
                            return;
                        }

                        // Replace the brackets by an identifier.
                        if (!node.optional) {
                            yield fixer.insertTextBefore(
                                leftBracket,
                                astUtils.isDecimalInteger(node.object) ? " ." : "."
                            );
                        }
                        yield fixer.replaceTextRange(
                            [leftBracket.range[0], rightBracket.range[1]],
                            value
                        );

                        // Insert a space after the property if it will be connected to the next token.
                        if (
                            nextToken &&
                            rightBracket.range[1] === nextToken.range[0] &&
                            !astUtils.canTokensBeAdjacent(String(value), nextToken)
                        ) {
                            yield fixer.insertTextAfter(node, " ");
                        }
                    }
                });
            }
        }

        return {
            MemberExpression(node) {
                if (
                    node.computed &&
                    node.property.type === "Literal" &&
                    (literalTypesToCheck.has(typeof node.property.value) || astUtils.isNullLiteral(node.property))
                ) {
                    checkComputedProperty(node, node.property.value);
                }
                if (
                    node.computed &&
                    node.property.type === "TemplateLiteral" &&
                    node.property.expressions.length === 0
                ) {
                    checkComputedProperty(node, node.property.quasis[0].value.cooked);
                }
                if (
                    !allowKeywords &&
                    !node.computed &&
                    keywords.indexOf(String(node.property.name)) !== -1
                ) {
                    context.report({
                        node: node.property,
                        messageId: "useBrackets",
                        data: {
                            key: node.property.name
                        },
                        *fix(fixer) {
                            const dotToken = sourceCode.getTokenBefore(node.property);

                            // A statement that starts with `let[` is parsed as a destructuring variable declaration, not a MemberExpression.
                            if (node.object.type === "Identifier" && node.object.name === "let" && !node.optional) {
                                return;
                            }

                            // Don't perform any fixes if there are comments between the dot and the property name.
                            if (sourceCode.commentsExistBetween(dotToken, node.property)) {
                                return;
                            }

                            // Replace the identifier to brackets.
                            if (!node.optional) {
                                yield fixer.remove(dotToken);
                            }
                            yield fixer.replaceText(node.property, `["${node.property.name}"]`);
                        }
                    });
                }
            }
        };
    }
};