4c6ac16a427670ec1880a09ac31534381926215b
[platform/framework/web/crosswalk-tizen.git] /
1 /**
2  * @fileoverview Rule to flag unnecessary strict directives.
3  * @author Ian Christian Myers
4  * @copyright 2014 Ian Christian Myers. All rights reserved.
5  */
6 "use strict";
7
8 //------------------------------------------------------------------------------
9 // Rule Definition
10 //------------------------------------------------------------------------------
11
12 module.exports = function(context) {
13
14     function directives(block) {
15         var ds = [], body = block.body, e, i, l;
16
17         if (body) {
18             for (i = 0, l = body.length; i < l; ++i) {
19                 e = body[i];
20
21                 if (
22                     e.type === "ExpressionStatement" &&
23                     e.expression.type === "Literal" &&
24                     typeof e.expression.value === "string"
25                 ) {
26                     ds.push(e.expression);
27                 } else {
28                     break;
29                 }
30             }
31         }
32
33         return ds;
34     }
35
36     function isStrict(directive) {
37         return directive.value === "use strict";
38     }
39
40     function checkForUnnecessaryUseStrict(node) {
41         var useStrictDirectives = directives(node).filter(isStrict),
42             scope,
43             upper;
44
45         switch (useStrictDirectives.length) {
46             case 0:
47                 break;
48
49             case 1:
50                 scope = context.getScope();
51                 upper = scope.upper;
52
53                 if (upper && upper.functionExpressionScope) {
54                     upper = upper.upper;
55                 }
56
57                 if (upper && upper.isStrict) {
58                     context.report(useStrictDirectives[0], "Unnecessary 'use strict'.");
59                 }
60                 break;
61
62             default:
63                 context.report(useStrictDirectives[1], "Multiple 'use strict' directives.");
64         }
65     }
66
67     return {
68
69         "Program": checkForUnnecessaryUseStrict,
70
71         "ArrowFunctionExpression": function(node) {
72             checkForUnnecessaryUseStrict(node.body);
73         },
74
75         "FunctionExpression": function(node) {
76             checkForUnnecessaryUseStrict(node.body);
77         },
78
79         "FunctionDeclaration": function(node) {
80             checkForUnnecessaryUseStrict(node.body);
81         }
82     };
83
84 };