UNPKG

2.19 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag when re-assigning native objects
3 * @author Ilya Volodin
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = function(context) {
13 var config = context.options[0];
14 var exceptions = (config && config.exceptions) || [];
15
16 /**
17 * Reports write references.
18 * @param {Reference} reference - A reference to check.
19 * @param {int} index - The index of the reference in the references.
20 * @param {Reference[]} references - The array that the reference belongs to.
21 * @returns {void}
22 */
23 function checkReference(reference, index, references) {
24 var identifier = reference.identifier;
25
26 if (reference.init === false &&
27 reference.isWrite() &&
28 // Destructuring assignments can have multiple default value,
29 // so possibly there are multiple writeable references for the same identifier.
30 (index === 0 || references[index - 1].identifier !== identifier)
31 ) {
32 context.report({
33 node: identifier,
34 message: "{{name}} is a read-only native object.",
35 data: identifier
36 });
37 }
38 }
39
40 /**
41 * Reports write references if a given variable is readonly builtin.
42 * @param {Variable} variable - A variable to check.
43 * @returns {void}
44 */
45 function checkVariable(variable) {
46 if (variable.writeable === false && exceptions.indexOf(variable.name) === -1) {
47 variable.references.forEach(checkReference);
48 }
49 }
50
51 return {
52 "Program": function() {
53 var globalScope = context.getScope();
54 globalScope.variables.forEach(checkVariable);
55 }
56 };
57};
58
59module.exports.schema = [
60 {
61 "type": "object",
62 "properties": {
63 "exceptions": {
64 "type": "array",
65 "items": {"type": "string"},
66 "uniqueItems": true
67 }
68 },
69 "additionalProperties": false
70 }
71];