summaryrefslogtreecommitdiff
path: root/tools/eslint/lib/rules/strict.js
blob: 433b47136797c6f770036c47edf5e292297da580 (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
/**
 * @fileoverview Rule to control usage of strict mode directives.
 * @author Brandon Mills
 */

"use strict";

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

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

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

const messages = {
    function: "Use the function form of 'use strict'.",
    global: "Use the global form of 'use strict'.",
    multiple: "Multiple 'use strict' directives.",
    never: "Strict mode is not permitted.",
    unnecessary: "Unnecessary 'use strict' directive.",
    module: "'use strict' is unnecessary inside of modules.",
    implied: "'use strict' is unnecessary when implied strict mode is enabled.",
    unnecessaryInClasses: "'use strict' is unnecessary inside of classes.",
    nonSimpleParameterList: "'use strict' directive inside a function with non-simple parameter list throws a syntax error since ES2016.",
    wrap: "Wrap {{name}} in a function with 'use strict' directive."
};

/**
 * Gets all of the Use Strict Directives in the Directive Prologue of a group of
 * statements.
 * @param {ASTNode[]} statements Statements in the program or function body.
 * @returns {ASTNode[]} All of the Use Strict Directives.
 */
function getUseStrictDirectives(statements) {
    const directives = [];

    for (let i = 0; i < statements.length; i++) {
        const statement = statements[i];

        if (
            statement.type === "ExpressionStatement" &&
            statement.expression.type === "Literal" &&
            statement.expression.value === "use strict"
        ) {
            directives[i] = statement;
        } else {
            break;
        }
    }

    return directives;
}

/**
 * Checks whether a given parameter is a simple parameter.
 *
 * @param {ASTNode} node - A pattern node to check.
 * @returns {boolean} `true` if the node is an Identifier node.
 */
function isSimpleParameter(node) {
    return node.type === "Identifier";
}

/**
 * Checks whether a given parameter list is a simple parameter list.
 *
 * @param {ASTNode[]} params - A parameter list to check.
 * @returns {boolean} `true` if the every parameter is an Identifier node.
 */
function isSimpleParameterList(params) {
    return params.every(isSimpleParameter);
}

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

module.exports = {
    meta: {
        docs: {
            description: "require or disallow strict mode directives",
            category: "Strict Mode",
            recommended: false
        },

        schema: [
            {
                enum: ["never", "global", "function", "safe"]
            }
        ],

        fixable: "code"
    },

    create(context) {

        const ecmaFeatures = context.parserOptions.ecmaFeatures || {},
            scopes = [],
            classScopes = [];
        let mode = context.options[0] || "safe";

        if (ecmaFeatures.impliedStrict) {
            mode = "implied";
        } else if (mode === "safe") {
            mode = ecmaFeatures.globalReturn ? "global" : "function";
        }

        /**
         * Determines whether a reported error should be fixed, depending on the error type.
         * @param {string} errorType The type of error
         * @returns {boolean} `true` if the reported error should be fixed
         */
        function shouldFix(errorType) {
            return errorType === "multiple" || errorType === "unnecessary" || errorType === "module" || errorType === "implied" || errorType === "unnecessaryInClasses";
        }

        /**
         * Gets a fixer function to remove a given 'use strict' directive.
         * @param {ASTNode} node The directive that should be removed
         * @returns {Function} A fixer function
         */
        function getFixFunction(node) {
            return fixer => fixer.remove(node);
        }

        /**
         * Report a slice of an array of nodes with a given message.
         * @param {ASTNode[]} nodes Nodes.
         * @param {string} start Index to start from.
         * @param {string} end Index to end before.
         * @param {string} message Message to display.
         * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
         * @returns {void}
         */
        function reportSlice(nodes, start, end, message, fix) {
            nodes.slice(start, end).forEach(node => {
                context.report({ node, message, fix: fix ? getFixFunction(node) : null });
            });
        }

        /**
         * Report all nodes in an array with a given message.
         * @param {ASTNode[]} nodes Nodes.
         * @param {string} message Message to display.
         * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
         * @returns {void}
         */
        function reportAll(nodes, message, fix) {
            reportSlice(nodes, 0, nodes.length, message, fix);
        }

        /**
         * Report all nodes in an array, except the first, with a given message.
         * @param {ASTNode[]} nodes Nodes.
         * @param {string} message Message to display.
         * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
         * @returns {void}
         */
        function reportAllExceptFirst(nodes, message, fix) {
            reportSlice(nodes, 1, nodes.length, message, fix);
        }

        /**
         * Entering a function in 'function' mode pushes a new nested scope onto the
         * stack. The new scope is true if the nested function is strict mode code.
         * @param {ASTNode} node The function declaration or expression.
         * @param {ASTNode[]} useStrictDirectives The Use Strict Directives of the node.
         * @returns {void}
         */
        function enterFunctionInFunctionMode(node, useStrictDirectives) {
            const isInClass = classScopes.length > 0,
                isParentGlobal = scopes.length === 0 && classScopes.length === 0,
                isParentStrict = scopes.length > 0 && scopes[scopes.length - 1],
                isStrict = useStrictDirectives.length > 0;

            if (isStrict) {
                if (!isSimpleParameterList(node.params)) {
                    context.report({ node: useStrictDirectives[0], message: messages.nonSimpleParameterList });
                } else if (isParentStrict) {
                    context.report({ node: useStrictDirectives[0], message: messages.unnecessary, fix: getFixFunction(useStrictDirectives[0]) });
                } else if (isInClass) {
                    context.report({ node: useStrictDirectives[0], message: messages.unnecessaryInClasses, fix: getFixFunction(useStrictDirectives[0]) });
                }

                reportAllExceptFirst(useStrictDirectives, messages.multiple, true);
            } else if (isParentGlobal) {
                if (isSimpleParameterList(node.params)) {
                    context.report({ node, message: messages.function });
                } else {
                    context.report({
                        node,
                        message: messages.wrap,
                        data: { name: astUtils.getFunctionNameWithKind(node) }
                    });
                }
            }

            scopes.push(isParentStrict || isStrict);
        }

        /**
         * Exiting a function in 'function' mode pops its scope off the stack.
         * @returns {void}
         */
        function exitFunctionInFunctionMode() {
            scopes.pop();
        }

        /**
         * Enter a function and either:
         * - Push a new nested scope onto the stack (in 'function' mode).
         * - Report all the Use Strict Directives (in the other modes).
         * @param {ASTNode} node The function declaration or expression.
         * @returns {void}
         */
        function enterFunction(node) {
            const isBlock = node.body.type === "BlockStatement",
                useStrictDirectives = isBlock
                    ? getUseStrictDirectives(node.body.body) : [];

            if (mode === "function") {
                enterFunctionInFunctionMode(node, useStrictDirectives);
            } else if (useStrictDirectives.length > 0) {
                if (isSimpleParameterList(node.params)) {
                    reportAll(useStrictDirectives, messages[mode], shouldFix(mode));
                } else {
                    context.report({ node: useStrictDirectives[0], message: messages.nonSimpleParameterList });
                    reportAllExceptFirst(useStrictDirectives, messages.multiple, true);
                }
            }
        }

        const rule = {
            Program(node) {
                const useStrictDirectives = getUseStrictDirectives(node.body);

                if (node.sourceType === "module") {
                    mode = "module";
                }

                if (mode === "global") {
                    if (node.body.length > 0 && useStrictDirectives.length === 0) {
                        context.report({ node, message: messages.global });
                    }
                    reportAllExceptFirst(useStrictDirectives, messages.multiple, true);
                } else {
                    reportAll(useStrictDirectives, messages[mode], shouldFix(mode));
                }
            },
            FunctionDeclaration: enterFunction,
            FunctionExpression: enterFunction,
            ArrowFunctionExpression: enterFunction
        };

        if (mode === "function") {
            Object.assign(rule, {

                // Inside of class bodies are always strict mode.
                ClassBody() {
                    classScopes.push(true);
                },
                "ClassBody:exit"() {
                    classScopes.pop();
                },

                "FunctionDeclaration:exit": exitFunctionInFunctionMode,
                "FunctionExpression:exit": exitFunctionInFunctionMode,
                "ArrowFunctionExpression:exit": exitFunctionInFunctionMode
            });
        }

        return rule;
    }
};