summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/prefer-rest-params.js
blob: 5a9164ed7f4e47fa498b002fb5e519d8c1832db3 (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
/**
 * @fileoverview Rule to
 * @author Toru Nagashima
 */

"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) {
    let variables = scope.variables;

    for (let i = 0; i < variables.length; ++i) {
        let 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 = {
    meta: {
        docs: {
            description: "require rest parameters instead of `arguments`",
            category: "ECMAScript 6",
            recommended: false
        },

        schema: []
    },

    create: 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() {
            let argumentsVar = getVariableOfArguments(context.getScope());

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

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