no-extra-bind.js 7.39 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
/**
 * @fileoverview Rule to flag unnecessary bind calls
 * @author Bence Dányi <bence@danyi.me>
 */
"use strict";

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

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

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

const SIDE_EFFECT_FREE_NODE_TYPES = new Set(["Literal", "Identifier", "ThisExpression", "FunctionExpression"]);

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

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

        docs: {
            description: "disallow unnecessary calls to `.bind()`",
            category: "Best Practices",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-extra-bind"
        },

        schema: [],
        fixable: "code",

        messages: {
            unexpected: "The function binding is unnecessary."
        }
    },

    create(context) {
        const sourceCode = context.getSourceCode();
        let scopeInfo = null;

        /**
         * Checks if a node is free of side effects.
         *
         * This check is stricter than it needs to be, in order to keep the implementation simple.
         * @param {ASTNode} node A node to check.
         * @returns {boolean} True if the node is known to be side-effect free, false otherwise.
         */
        function isSideEffectFree(node) {
            return SIDE_EFFECT_FREE_NODE_TYPES.has(node.type);
        }

        /**
         * Reports a given function node.
         * @param {ASTNode} node A node to report. This is a FunctionExpression or
         *      an ArrowFunctionExpression.
         * @returns {void}
         */
        function report(node) {
            const memberNode = node.parent;
            const callNode = memberNode.parent.type === "ChainExpression"
                ? memberNode.parent.parent
                : memberNode.parent;

            context.report({
                node: callNode,
                messageId: "unexpected",
                loc: memberNode.property.loc,

                fix(fixer) {
                    if (!isSideEffectFree(callNode.arguments[0])) {
                        return null;
                    }

                    /*
                     * The list of the first/last token pair of a removal range.
                     * This is two parts because closing parentheses may exist between the method name and arguments.
                     * E.g. `(function(){}.bind ) (obj)`
                     *                    ^^^^^   ^^^^^ < removal ranges
                     * E.g. `(function(){}?.['bind'] ) ?.(obj)`
                     *                    ^^^^^^^^^^   ^^^^^^^ < removal ranges
                     */
                    const tokenPairs = [
                        [

                            // `.`, `?.`, or `[` token.
                            sourceCode.getTokenAfter(
                                memberNode.object,
                                astUtils.isNotClosingParenToken
                            ),

                            // property name or `]` token.
                            sourceCode.getLastToken(memberNode)
                        ],
                        [

                            // `?.` or `(` token of arguments.
                            sourceCode.getTokenAfter(
                                memberNode,
                                astUtils.isNotClosingParenToken
                            ),

                            // `)` token of arguments.
                            sourceCode.getLastToken(callNode)
                        ]
                    ];
                    const firstTokenToRemove = tokenPairs[0][0];
                    const lastTokenToRemove = tokenPairs[1][1];

                    if (sourceCode.commentsExistBetween(firstTokenToRemove, lastTokenToRemove)) {
                        return null;
                    }

                    return tokenPairs.map(([start, end]) =>
                        fixer.removeRange([start.range[0], end.range[1]]));
                }
            });
        }

        /**
         * Checks whether or not a given function node is the callee of `.bind()`
         * method.
         *
         * e.g. `(function() {}.bind(foo))`
         * @param {ASTNode} node A node to report. This is a FunctionExpression or
         *      an ArrowFunctionExpression.
         * @returns {boolean} `true` if the node is the callee of `.bind()` method.
         */
        function isCalleeOfBindMethod(node) {
            if (!astUtils.isSpecificMemberAccess(node.parent, null, "bind")) {
                return false;
            }

            // The node of `*.bind` member access.
            const bindNode = node.parent.parent.type === "ChainExpression"
                ? node.parent.parent
                : node.parent;

            return (
                bindNode.parent.type === "CallExpression" &&
                bindNode.parent.callee === bindNode &&
                bindNode.parent.arguments.length === 1 &&
                bindNode.parent.arguments[0].type !== "SpreadElement"
            );
        }

        /**
         * Adds a scope information object to the stack.
         * @param {ASTNode} node A node to add. This node is a FunctionExpression
         *      or a FunctionDeclaration node.
         * @returns {void}
         */
        function enterFunction(node) {
            scopeInfo = {
                isBound: isCalleeOfBindMethod(node),
                thisFound: false,
                upper: scopeInfo
            };
        }

        /**
         * Removes the scope information object from the top of the stack.
         * At the same time, this reports the function node if the function has
         * `.bind()` and the `this` keywords found.
         * @param {ASTNode} node A node to remove. This node is a
         *      FunctionExpression or a FunctionDeclaration node.
         * @returns {void}
         */
        function exitFunction(node) {
            if (scopeInfo.isBound && !scopeInfo.thisFound) {
                report(node);
            }

            scopeInfo = scopeInfo.upper;
        }

        /**
         * Reports a given arrow function if the function is callee of `.bind()`
         * method.
         * @param {ASTNode} node A node to report. This node is an
         *      ArrowFunctionExpression.
         * @returns {void}
         */
        function exitArrowFunction(node) {
            if (isCalleeOfBindMethod(node)) {
                report(node);
            }
        }

        /**
         * Set the mark as the `this` keyword was found in this scope.
         * @returns {void}
         */
        function markAsThisFound() {
            if (scopeInfo) {
                scopeInfo.thisFound = true;
            }
        }

        return {
            "ArrowFunctionExpression:exit": exitArrowFunction,
            FunctionDeclaration: enterFunction,
            "FunctionDeclaration:exit": exitFunction,
            FunctionExpression: enterFunction,
            "FunctionExpression:exit": exitFunction,
            ThisExpression: markAsThisFound
        };
    }
};