summaryrefslogtreecommitdiff
path: root/tools/node_modules/eslint/lib/rules/no-eval.js
blob: 9e56fb00b9fc5b17560162d610b6d8f9528be0c8 (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
/**
 * @fileoverview Rule to flag use of eval() statement
 * @author Nicholas C. Zakas
 */

"use strict";

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

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

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

const candidatesOfGlobalObject = Object.freeze([
    "global",
    "window"
]);

/**
 * Checks a given node is a Identifier node of the specified name.
 * @param {ASTNode} node A node to check.
 * @param {string} name A name to check.
 * @returns {boolean} `true` if the node is a Identifier node of the name.
 */
function isIdentifier(node, name) {
    return node.type === "Identifier" && node.name === name;
}

/**
 * Checks a given node is a Literal node of the specified string value.
 * @param {ASTNode} node A node to check.
 * @param {string} name A name to check.
 * @returns {boolean} `true` if the node is a Literal node of the name.
 */
function isConstant(node, name) {
    switch (node.type) {
        case "Literal":
            return node.value === name;

        case "TemplateLiteral":
            return (
                node.expressions.length === 0 &&
                node.quasis[0].value.cooked === name
            );

        default:
            return false;
    }
}

/**
 * Checks a given node is a MemberExpression node which has the specified name's
 * property.
 * @param {ASTNode} node A node to check.
 * @param {string} name A name to check.
 * @returns {boolean} `true` if the node is a MemberExpression node which has
 *      the specified name's property
 */
function isMember(node, name) {
    return (
        node.type === "MemberExpression" &&
        (node.computed ? isConstant : isIdentifier)(node.property, name)
    );
}

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

module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "disallow the use of `eval()`",
            category: "Best Practices",
            recommended: false,
            url: "https://eslint.org/docs/rules/no-eval"
        },

        schema: [
            {
                type: "object",
                properties: {
                    allowIndirect: { type: "boolean", default: false }
                },
                additionalProperties: false
            }
        ],

        messages: {
            unexpected: "eval can be harmful."
        }
    },

    create(context) {
        const allowIndirect = Boolean(
            context.options[0] &&
            context.options[0].allowIndirect
        );
        const sourceCode = context.getSourceCode();
        let funcInfo = null;

        /**
         * Pushs a variable scope (Program or Function) information to the stack.
         *
         * This is used in order to check whether or not `this` binding is a
         * reference to the global object.
         * @param {ASTNode} node A node of the scope. This is one of Program,
         *      FunctionDeclaration, FunctionExpression, and ArrowFunctionExpression.
         * @returns {void}
         */
        function enterVarScope(node) {
            const strict = context.getScope().isStrict;

            funcInfo = {
                upper: funcInfo,
                node,
                strict,
                defaultThis: false,
                initialized: strict
            };
        }

        /**
         * Pops a variable scope from the stack.
         * @returns {void}
         */
        function exitVarScope() {
            funcInfo = funcInfo.upper;
        }

        /**
         * Reports a given node.
         *
         * `node` is `Identifier` or `MemberExpression`.
         * The parent of `node` might be `CallExpression`.
         *
         * The location of the report is always `eval` `Identifier` (or possibly
         * `Literal`). The type of the report is `CallExpression` if the parent is
         * `CallExpression`. Otherwise, it's the given node type.
         * @param {ASTNode} node A node to report.
         * @returns {void}
         */
        function report(node) {
            const parent = node.parent;
            const locationNode = node.type === "MemberExpression"
                ? node.property
                : node;

            const reportNode = parent.type === "CallExpression" && parent.callee === node
                ? parent
                : node;

            context.report({
                node: reportNode,
                loc: locationNode.loc.start,
                messageId: "unexpected"
            });
        }

        /**
         * Reports accesses of `eval` via the global object.
         * @param {eslint-scope.Scope} globalScope The global scope.
         * @returns {void}
         */
        function reportAccessingEvalViaGlobalObject(globalScope) {
            for (let i = 0; i < candidatesOfGlobalObject.length; ++i) {
                const name = candidatesOfGlobalObject[i];
                const variable = astUtils.getVariableByName(globalScope, name);

                if (!variable) {
                    continue;
                }

                const references = variable.references;

                for (let j = 0; j < references.length; ++j) {
                    const identifier = references[j].identifier;
                    let node = identifier.parent;

                    // To detect code like `window.window.eval`.
                    while (isMember(node, name)) {
                        node = node.parent;
                    }

                    // Reports.
                    if (isMember(node, "eval")) {
                        report(node);
                    }
                }
            }
        }

        /**
         * Reports all accesses of `eval` (excludes direct calls to eval).
         * @param {eslint-scope.Scope} globalScope The global scope.
         * @returns {void}
         */
        function reportAccessingEval(globalScope) {
            const variable = astUtils.getVariableByName(globalScope, "eval");

            if (!variable) {
                return;
            }

            const references = variable.references;

            for (let i = 0; i < references.length; ++i) {
                const reference = references[i];
                const id = reference.identifier;

                if (id.name === "eval" && !astUtils.isCallee(id)) {

                    // Is accessing to eval (excludes direct calls to eval)
                    report(id);
                }
            }
        }

        if (allowIndirect) {

            // Checks only direct calls to eval. It's simple!
            return {
                "CallExpression:exit"(node) {
                    const callee = node.callee;

                    if (isIdentifier(callee, "eval")) {
                        report(callee);
                    }
                }
            };
        }

        return {
            "CallExpression:exit"(node) {
                const callee = node.callee;

                if (isIdentifier(callee, "eval")) {
                    report(callee);
                }
            },

            Program(node) {
                const scope = context.getScope(),
                    features = context.parserOptions.ecmaFeatures || {},
                    strict =
                        scope.isStrict ||
                        node.sourceType === "module" ||
                        (features.globalReturn && scope.childScopes[0].isStrict);

                funcInfo = {
                    upper: null,
                    node,
                    strict,
                    defaultThis: true,
                    initialized: true
                };
            },

            "Program:exit"() {
                const globalScope = context.getScope();

                exitVarScope();
                reportAccessingEval(globalScope);
                reportAccessingEvalViaGlobalObject(globalScope);
            },

            FunctionDeclaration: enterVarScope,
            "FunctionDeclaration:exit": exitVarScope,
            FunctionExpression: enterVarScope,
            "FunctionExpression:exit": exitVarScope,
            ArrowFunctionExpression: enterVarScope,
            "ArrowFunctionExpression:exit": exitVarScope,

            ThisExpression(node) {
                if (!isMember(node.parent, "eval")) {
                    return;
                }

                /*
                 * `this.eval` is found.
                 * Checks whether or not the value of `this` is the global object.
                 */
                if (!funcInfo.initialized) {
                    funcInfo.initialized = true;
                    funcInfo.defaultThis = astUtils.isDefaultThisBinding(
                        funcInfo.node,
                        sourceCode
                    );
                }

                if (!funcInfo.strict && funcInfo.defaultThis) {

                    // `this.eval` is possible built-in `eval`.
                    report(node.parent);
                }
            }
        };

    }
};