summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/no-native-reassign.js
blob: b4323369e42c03b7ca2febec3b60539b68baa1b1 (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
/**
 * @fileoverview Rule to flag when re-assigning native objects
 * @author Ilya Volodin
 */

"use strict";

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

module.exports = function(context) {
    var config = context.options[0];
    var exceptions = (config && config.exceptions) || [];

    /**
     * Reports write references.
     * @param {Reference} reference - A reference to check.
     * @param {int} index - The index of the reference in the references.
     * @param {Reference[]} references - The array that the reference belongs to.
     * @returns {void}
     */
    function checkReference(reference, index, references) {
        var identifier = reference.identifier;

        if (reference.init === false &&
            reference.isWrite() &&

            // Destructuring assignments can have multiple default value,
            // so possibly there are multiple writeable references for the same identifier.
            (index === 0 || references[index - 1].identifier !== identifier)
        ) {
            context.report({
                node: identifier,
                message: "{{name}} is a read-only native object.",
                data: identifier
            });
        }
    }

    /**
     * Reports write references if a given variable is readonly builtin.
     * @param {Variable} variable - A variable to check.
     * @returns {void}
     */
    function checkVariable(variable) {
        if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) {
            variable.references.forEach(checkReference);
        }
    }

    return {
        "Program": function() {
            var globalScope = context.getScope();

            globalScope.variables.forEach(checkVariable);
        }
    };
};

module.exports.schema = [
    {
        "type": "object",
        "properties": {
            "exceptions": {
                "type": "array",
                "items": {"type": "string"},
                "uniqueItems": true
            }
        },
        "additionalProperties": false
    }
];