1 | /**
|
2 | * @fileoverview Rule to ensure code is running in strict mode.
|
3 | * @author Nicholas C. Zakas
|
4 | */
|
5 | ;
|
6 |
|
7 | //------------------------------------------------------------------------------
|
8 | // Rule Definition
|
9 | //------------------------------------------------------------------------------
|
10 |
|
11 | module.exports = function(context) {
|
12 |
|
13 | var scopes = [];
|
14 |
|
15 | /**
|
16 | * When you enter a scope, push the strict value from the previous scope
|
17 | * onto the stack.
|
18 | * @returns {void}
|
19 | * @private
|
20 | */
|
21 | function enterScope() {
|
22 | scopes.push(scopes[scopes.length - 1] || false);
|
23 | }
|
24 |
|
25 | /**
|
26 | * When you exit a scope, pop off the top scope and see if it's true or
|
27 | * false.
|
28 | * @param {ASTNode} node The AST node being checked.
|
29 | * @returns {void}
|
30 | * @private
|
31 | */
|
32 | function exitScope(node) {
|
33 | var isStrict = scopes.pop();
|
34 |
|
35 | if (!isStrict && node.type !== "Program") {
|
36 | context.report(node, "Missing \"use strict\" statement.");
|
37 | }
|
38 | }
|
39 |
|
40 | return {
|
41 |
|
42 | "Program": enterScope,
|
43 | "FunctionDeclaration": enterScope,
|
44 | "FunctionExpression": enterScope,
|
45 |
|
46 | "Program:exit": exitScope,
|
47 | "FunctionDeclaration:exit": exitScope,
|
48 | "FunctionExpression:exit": exitScope,
|
49 |
|
50 | "ExpressionStatement": function(node) {
|
51 |
|
52 | if (node.expression.value === "use strict") {
|
53 | scopes[scopes.length] = true;
|
54 | }
|
55 |
|
56 | }
|
57 | };
|
58 |
|
59 | };
|