UNPKG

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