summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/prefer-rest-params.js
blob: d52c1164cbf7d416d31b44b544820f8808e88487 (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
/**
 * @fileoverview Rule to
 * @author Toru Nagashima
 * @copyright 2015 Toru Nagashima. All rights reserved.
 * See LICENSE file in root directory for full license.
 */

"use strict";

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

/**
 * Gets the variable object of `arguments` which is defined implicitly.
 * @param {escope.Scope} scope - A scope to get.
 * @returns {escope.Variable} The found variable object.
 */
function getVariableOfArguments(scope) {
    var variables = scope.variables;

    for (var i = 0; i < variables.length; ++i) {
        var variable = variables[i];

        if (variable.name === "arguments") {

            // If there was a parameter which is named "arguments", the implicit "arguments" is not defined.
            // So does fast return with null.
            return (variable.identifiers.length === 0) ? variable : null;
        }
    }

    /* istanbul ignore next : unreachable */
    return null;
}

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

module.exports = function(context) {

    /**
     * Reports a given reference.
     *
     * @param {escope.Reference} reference - A reference to report.
     * @returns {void}
     */
    function report(reference) {
        context.report({
            node: reference.identifier,
            message: "Use the rest parameters instead of 'arguments'."
        });
    }

    /**
     * Reports references of the implicit `arguments` variable if exist.
     *
     * @returns {void}
     */
    function checkForArguments() {
        var argumentsVar = getVariableOfArguments(context.getScope());

        if (argumentsVar) {
            argumentsVar.references.forEach(report);
        }
    }

    return {
        FunctionDeclaration: checkForArguments,
        FunctionExpression: checkForArguments
    };
};

module.exports.schema = [];