UNPKG

10.5 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to control usage of strict mode directives.
3 * @author Brandon Mills
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Requirements
10//------------------------------------------------------------------------------
11
12const astUtils = require("../ast-utils");
13
14//------------------------------------------------------------------------------
15// Helpers
16//------------------------------------------------------------------------------
17
18const messages = {
19 function: "Use the function form of 'use strict'.",
20 global: "Use the global form of 'use strict'.",
21 multiple: "Multiple 'use strict' directives.",
22 never: "Strict mode is not permitted.",
23 unnecessary: "Unnecessary 'use strict' directive.",
24 module: "'use strict' is unnecessary inside of modules.",
25 implied: "'use strict' is unnecessary when implied strict mode is enabled.",
26 unnecessaryInClasses: "'use strict' is unnecessary inside of classes.",
27 nonSimpleParameterList: "'use strict' directive inside a function with non-simple parameter list throws a syntax error since ES2016.",
28 wrap: "Wrap {{name}} in a function with 'use strict' directive."
29};
30
31/**
32 * Gets all of the Use Strict Directives in the Directive Prologue of a group of
33 * statements.
34 * @param {ASTNode[]} statements Statements in the program or function body.
35 * @returns {ASTNode[]} All of the Use Strict Directives.
36 */
37function getUseStrictDirectives(statements) {
38 const directives = [];
39
40 for (let i = 0; i < statements.length; i++) {
41 const statement = statements[i];
42
43 if (
44 statement.type === "ExpressionStatement" &&
45 statement.expression.type === "Literal" &&
46 statement.expression.value === "use strict"
47 ) {
48 directives[i] = statement;
49 } else {
50 break;
51 }
52 }
53
54 return directives;
55}
56
57/**
58 * Checks whether a given parameter is a simple parameter.
59 *
60 * @param {ASTNode} node - A pattern node to check.
61 * @returns {boolean} `true` if the node is an Identifier node.
62 */
63function isSimpleParameter(node) {
64 return node.type === "Identifier";
65}
66
67/**
68 * Checks whether a given parameter list is a simple parameter list.
69 *
70 * @param {ASTNode[]} params - A parameter list to check.
71 * @returns {boolean} `true` if the every parameter is an Identifier node.
72 */
73function isSimpleParameterList(params) {
74 return params.every(isSimpleParameter);
75}
76
77//------------------------------------------------------------------------------
78// Rule Definition
79//------------------------------------------------------------------------------
80
81module.exports = {
82 meta: {
83 docs: {
84 description: "require or disallow strict mode directives",
85 category: "Strict Mode",
86 recommended: false,
87 url: "https://eslint.org/docs/rules/strict"
88 },
89
90 schema: [
91 {
92 enum: ["never", "global", "function", "safe"]
93 }
94 ],
95
96 fixable: "code"
97 },
98
99 create(context) {
100
101 const ecmaFeatures = context.parserOptions.ecmaFeatures || {},
102 scopes = [],
103 classScopes = [];
104 let mode = context.options[0] || "safe";
105
106 if (ecmaFeatures.impliedStrict) {
107 mode = "implied";
108 } else if (mode === "safe") {
109 mode = ecmaFeatures.globalReturn ? "global" : "function";
110 }
111
112 /**
113 * Determines whether a reported error should be fixed, depending on the error type.
114 * @param {string} errorType The type of error
115 * @returns {boolean} `true` if the reported error should be fixed
116 */
117 function shouldFix(errorType) {
118 return errorType === "multiple" || errorType === "unnecessary" || errorType === "module" || errorType === "implied" || errorType === "unnecessaryInClasses";
119 }
120
121 /**
122 * Gets a fixer function to remove a given 'use strict' directive.
123 * @param {ASTNode} node The directive that should be removed
124 * @returns {Function} A fixer function
125 */
126 function getFixFunction(node) {
127 return fixer => fixer.remove(node);
128 }
129
130 /**
131 * Report a slice of an array of nodes with a given message.
132 * @param {ASTNode[]} nodes Nodes.
133 * @param {string} start Index to start from.
134 * @param {string} end Index to end before.
135 * @param {string} message Message to display.
136 * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
137 * @returns {void}
138 */
139 function reportSlice(nodes, start, end, message, fix) {
140 nodes.slice(start, end).forEach(node => {
141 context.report({ node, message, fix: fix ? getFixFunction(node) : null });
142 });
143 }
144
145 /**
146 * Report all nodes in an array with a given message.
147 * @param {ASTNode[]} nodes Nodes.
148 * @param {string} message Message to display.
149 * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
150 * @returns {void}
151 */
152 function reportAll(nodes, message, fix) {
153 reportSlice(nodes, 0, nodes.length, message, fix);
154 }
155
156 /**
157 * Report all nodes in an array, except the first, with a given message.
158 * @param {ASTNode[]} nodes Nodes.
159 * @param {string} message Message to display.
160 * @param {boolean} fix `true` if the directive should be fixed (i.e. removed)
161 * @returns {void}
162 */
163 function reportAllExceptFirst(nodes, message, fix) {
164 reportSlice(nodes, 1, nodes.length, message, fix);
165 }
166
167 /**
168 * Entering a function in 'function' mode pushes a new nested scope onto the
169 * stack. The new scope is true if the nested function is strict mode code.
170 * @param {ASTNode} node The function declaration or expression.
171 * @param {ASTNode[]} useStrictDirectives The Use Strict Directives of the node.
172 * @returns {void}
173 */
174 function enterFunctionInFunctionMode(node, useStrictDirectives) {
175 const isInClass = classScopes.length > 0,
176 isParentGlobal = scopes.length === 0 && classScopes.length === 0,
177 isParentStrict = scopes.length > 0 && scopes[scopes.length - 1],
178 isStrict = useStrictDirectives.length > 0;
179
180 if (isStrict) {
181 if (!isSimpleParameterList(node.params)) {
182 context.report({ node: useStrictDirectives[0], message: messages.nonSimpleParameterList });
183 } else if (isParentStrict) {
184 context.report({ node: useStrictDirectives[0], message: messages.unnecessary, fix: getFixFunction(useStrictDirectives[0]) });
185 } else if (isInClass) {
186 context.report({ node: useStrictDirectives[0], message: messages.unnecessaryInClasses, fix: getFixFunction(useStrictDirectives[0]) });
187 }
188
189 reportAllExceptFirst(useStrictDirectives, messages.multiple, true);
190 } else if (isParentGlobal) {
191 if (isSimpleParameterList(node.params)) {
192 context.report({ node, message: messages.function });
193 } else {
194 context.report({
195 node,
196 message: messages.wrap,
197 data: { name: astUtils.getFunctionNameWithKind(node) }
198 });
199 }
200 }
201
202 scopes.push(isParentStrict || isStrict);
203 }
204
205 /**
206 * Exiting a function in 'function' mode pops its scope off the stack.
207 * @returns {void}
208 */
209 function exitFunctionInFunctionMode() {
210 scopes.pop();
211 }
212
213 /**
214 * Enter a function and either:
215 * - Push a new nested scope onto the stack (in 'function' mode).
216 * - Report all the Use Strict Directives (in the other modes).
217 * @param {ASTNode} node The function declaration or expression.
218 * @returns {void}
219 */
220 function enterFunction(node) {
221 const isBlock = node.body.type === "BlockStatement",
222 useStrictDirectives = isBlock
223 ? getUseStrictDirectives(node.body.body) : [];
224
225 if (mode === "function") {
226 enterFunctionInFunctionMode(node, useStrictDirectives);
227 } else if (useStrictDirectives.length > 0) {
228 if (isSimpleParameterList(node.params)) {
229 reportAll(useStrictDirectives, messages[mode], shouldFix(mode));
230 } else {
231 context.report({ node: useStrictDirectives[0], message: messages.nonSimpleParameterList });
232 reportAllExceptFirst(useStrictDirectives, messages.multiple, true);
233 }
234 }
235 }
236
237 const rule = {
238 Program(node) {
239 const useStrictDirectives = getUseStrictDirectives(node.body);
240
241 if (node.sourceType === "module") {
242 mode = "module";
243 }
244
245 if (mode === "global") {
246 if (node.body.length > 0 && useStrictDirectives.length === 0) {
247 context.report({ node, message: messages.global });
248 }
249 reportAllExceptFirst(useStrictDirectives, messages.multiple, true);
250 } else {
251 reportAll(useStrictDirectives, messages[mode], shouldFix(mode));
252 }
253 },
254 FunctionDeclaration: enterFunction,
255 FunctionExpression: enterFunction,
256 ArrowFunctionExpression: enterFunction
257 };
258
259 if (mode === "function") {
260 Object.assign(rule, {
261
262 // Inside of class bodies are always strict mode.
263 ClassBody() {
264 classScopes.push(true);
265 },
266 "ClassBody:exit"() {
267 classScopes.pop();
268 },
269
270 "FunctionDeclaration:exit": exitFunctionInFunctionMode,
271 "FunctionExpression:exit": exitFunctionInFunctionMode,
272 "ArrowFunctionExpression:exit": exitFunctionInFunctionMode
273 });
274 }
275
276 return rule;
277 }
278};