summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/no-invalid-this.js
blob: 37c67de0b5d5e826d1acba4165819a81d57b7673 (plain)
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/**
 * @fileoverview A rule to disallow `this` keywords outside of classes or class-like objects.
 * @author Toru Nagashima
 * @copyright 2015 Toru Nagashima. All rights reserved.
 * See LICENSE file in root directory for full license.
 */

"use strict";

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

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

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

var thisTagPattern = /^[\s\*]*@this/m;
var anyFunctionPattern = /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/;
var bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/;
var arrayOrTypedArrayPattern = /Array$/;
var arrayMethodPattern = /^(?:every|filter|find|findIndex|forEach|map|some)$/;

/**
 * Checks whether or not a node is a constructor.
 * @param {ASTNode} node - A function node to check.
 * @returns {boolean} Wehether or not a node is a constructor.
 */
function isES5Constructor(node) {
    return (
        node.id &&
        node.id.name[0] === node.id.name[0].toLocaleUpperCase()
    );
}

/**
 * Finds a function node from ancestors of a node.
 * @param {ASTNode} node - A start node to find.
 * @returns {Node|null} A found function node.
 */
function getUpperFunction(node) {
    while (node) {
        if (anyFunctionPattern.test(node.type)) {
            return node;
        }
        node = node.parent;
    }
    return null;
}

/**
 * Checks whether or not a node is callee.
 * @param {ASTNode} node - A node to check.
 * @returns {boolean} Whether or not the node is callee.
 */
function isCallee(node) {
    return node.parent.type === "CallExpression" && node.parent.callee === node;
}

/**
 * Checks whether or not a node is `Reclect.apply`.
 * @param {ASTNode} node - A node to check.
 * @returns {boolean} Whether or not the node is a `Reclect.apply`.
 */
function isReflectApply(node) {
    return (
        node.type === "MemberExpression" &&
        node.object.type === "Identifier" &&
        node.object.name === "Reflect" &&
        node.property.type === "Identifier" &&
        node.property.name === "apply" &&
        node.computed === false
    );
}

/**
 * Checks whether or not a node is `Array.from`.
 * @param {ASTNode} node - A node to check.
 * @returns {boolean} Whether or not the node is a `Array.from`.
 */
function isArrayFrom(node) {
    return (
        node.type === "MemberExpression" &&
        node.object.type === "Identifier" &&
        arrayOrTypedArrayPattern.test(node.object.name) &&
        node.property.type === "Identifier" &&
        node.property.name === "from" &&
        node.computed === false
    );
}

/**
 * Checks whether or not a node is a method which has `thisArg`.
 * @param {ASTNode} node - A node to check.
 * @returns {boolean} Whether or not the node is a method which has `thisArg`.
 */
function isMethodWhichHasThisArg(node) {
    while (node) {
        if (node.type === "Identifier") {
            return arrayMethodPattern.test(node.name);
        }
        if (node.type === "MemberExpression" && !node.computed) {
            node = node.property;
            continue;
        }

        break;
    }

    return false;
}

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

module.exports = function(context) {
    var stack = [],
        sourceCode = context.getSourceCode();


    /**
     * Checks whether or not a node has a `@this` tag in its comments.
     * @param {ASTNode} node - A node to check.
     * @returns {boolean} Whether or not the node has a `@this` tag in its comments.
     */
    function hasJSDocThisTag(node) {
        var jsdocComment = sourceCode.getJSDocComment(node);
        if (jsdocComment && thisTagPattern.test(jsdocComment.value)) {
            return true;
        }

        // Checks `@this` in its leading comments for callbacks,
        // because callbacks don't have its JSDoc comment.
        // e.g.
        //     sinon.test(/* @this sinon.Sandbox */function() { this.spy(); });
        return sourceCode.getComments(node).leading.some(function(comment) {
            return thisTagPattern.test(comment.value);
        });
    }

    /**
     * Checks whether or not a node has valid `this`.
     *
     * First, this checks the node:
     *
     * - The function name starts with uppercase (it's a constructor).
     * - The function has a JSDoc comment that has a @this tag.
     *
     * Next, this checks the location of the node.
     * If the location is below, this judges `this` is valid.
     *
     * - The location is on an object literal.
     * - The location assigns to a property.
     * - The location is on an ES2015 class.
     * - The location calls its `bind`/`call`/`apply` method directly.
     * - The function is a callback of array methods (such as `.forEach()`) if `thisArg` is given.
     *
     * @param {ASTNode} node - A node to check.
     * @returns {boolean} A found function node.
     */
    function hasValidThis(node) {
        if (isES5Constructor(node) || hasJSDocThisTag(node)) {
            return true;
        }

        while (node) {
            var parent = node.parent;
            switch (parent.type) {
                // Looks up the destination.
                // e.g.
                //   obj.foo = nativeFoo || function foo() { ... };
                case "LogicalExpression":
                case "ConditionalExpression":
                    node = parent;
                    break;

                // If the upper function is IIFE, checks the destination of the return value.
                // e.g.
                //   obj.foo = (function() {
                //     // setup...
                //     return function foo() { ... };
                //   })();
                case "ReturnStatement":
                    var func = getUpperFunction(parent);
                    if (func === null || !isCallee(func)) {
                        return false;
                    }
                    node = func.parent;
                    break;

                // e.g.
                //   var obj = { foo() { ... } };
                //   var obj = { foo: function() { ... } };
                case "Property":
                    return true;

                // e.g.
                //   obj.foo = foo() { ... };
                case "AssignmentExpression":
                    return (
                        parent.right === node &&
                        parent.left.type === "MemberExpression"
                    );

                // e.g.
                //   class A { constructor() { ... } }
                //   class A { foo() { ... } }
                //   class A { get foo() { ... } }
                //   class A { set foo() { ... } }
                //   class A { static foo() { ... } }
                case "MethodDefinition":
                    return !parent.static;

                // e.g.
                //   var foo = function foo() { ... }.bind(obj);
                //   (function foo() { ... }).call(obj);
                //   (function foo() { ... }).apply(obj, []);
                case "MemberExpression":
                    return (
                        parent.object === node &&
                        parent.property.type === "Identifier" &&
                        bindOrCallOrApplyPattern.test(parent.property.name) &&
                        isCallee(parent) &&
                        parent.parent.arguments.length > 0 &&
                        !astUtils.isNullOrUndefined(parent.parent.arguments[0])
                    );

                // e.g.
                //   Reflect.apply(function() {}, obj, []);
                //   Array.from([], function() {}, obj);
                //   list.forEach(function() {}, obj);
                case "CallExpression":
                    if (isReflectApply(parent.callee)) {
                        return (
                            parent.arguments.length === 3 &&
                            parent.arguments[0] === node &&
                            !astUtils.isNullOrUndefined(parent.arguments[1])
                        );
                    }
                    if (isArrayFrom(parent.callee)) {
                        return (
                            parent.arguments.length === 3 &&
                            parent.arguments[1] === node &&
                            !astUtils.isNullOrUndefined(parent.arguments[2])
                        );
                    }
                    if (isMethodWhichHasThisArg(parent.callee)) {
                        return (
                            parent.arguments.length === 2 &&
                            parent.arguments[0] === node &&
                            !astUtils.isNullOrUndefined(parent.arguments[1])
                        );
                    }
                    return false;

                // Otherwise `this` is invalid.
                default:
                    return false;
            }
        }

        /* istanbul ignore next */
        throw new Error("unreachable");
    }

    /**
     * Gets the current checking context.
     *
     * The return value has a flag that whether or not `this` keyword is valid.
     * The flag is initialized when got at the first time.
     *
     * @returns {{valid: boolean}}
     *   an object which has a flag that whether or not `this` keyword is valid.
     */
    stack.getCurrent = function() {
        var current = this[this.length - 1];
        if (!current.init) {
            current.init = true;
            current.valid = hasValidThis(current.node);
        }
        return current;
    };

    /**
     * Pushs new checking context into the stack.
     *
     * The checking context is not initialized yet.
     * Because most functions don't have `this` keyword.
     * When `this` keyword was found, the checking context is initialized.
     *
     * @param {ASTNode} node - A function node that was entered.
     * @returns {void}
     */
    function enterFunction(node) {
        // `this` can be invalid only under strict mode.
        stack.push({
            init: !context.getScope().isStrict,
            node: node,
            valid: true
        });
    }

    /**
     * Pops the current checking context from the stack.
     * @returns {void}
     */
    function exitFunction() {
        stack.pop();
    }

    return {
        // `this` is invalid only under strict mode.
        // Modules is always strict mode.
        "Program": function(node) {
            var scope = context.getScope();
            var features = context.ecmaFeatures;

            stack.push({
                init: true,
                node: node,
                valid: !(
                    scope.isStrict ||
                    features.modules ||
                    (features.globalReturn && scope.childScopes[0].isStrict)
                )
            });
        },
        "Program:exit": function() {
            stack.pop();
        },

        "FunctionDeclaration": enterFunction,
        "FunctionDeclaration:exit": exitFunction,
        "FunctionExpression": enterFunction,
        "FunctionExpression:exit": exitFunction,

        // Reports if `this` of the current context is invalid.
        "ThisExpression": function(node) {
            var current = stack.getCurrent();
            if (current && !current.valid) {
                context.report(node, "Unexpected `this`.");
            }
        }
    };
};

module.exports.schema = [];