7036f90e7c71be3072183f5f0aec5aeef7964e1c
[platform/framework/web/crosswalk-tizen.git] /
1 /**
2  * @fileoverview Flag expressions in statement position that do not side effect
3  * @author Michael Ficarra
4  * @copyright 2013 Michael Ficarra. All rights reserved.
5  */
6 "use strict";
7
8 //------------------------------------------------------------------------------
9 // Rule Definition
10 //------------------------------------------------------------------------------
11
12 module.exports = function(context) {
13
14     /**
15      * @param {ASTNode} node - any node
16      * @returns {Boolean} whether the given node structurally represents a directive
17      */
18     function looksLikeDirective(node) {
19         return node.type === "ExpressionStatement" &&
20             node.expression.type === "Literal" && typeof node.expression.value === "string";
21     }
22
23     /**
24      * @param {Function} predicate - ([a] -> Boolean) the function used to make the determination
25      * @param {a[]} list - the input list
26      * @returns {a[]} the leading sequence of members in the given list that pass the given predicate
27      */
28     function takeWhile(predicate, list) {
29         for (var i = 0, l = list.length; i < l; ++i) {
30             if (!predicate(list[i])) {
31                 break;
32             }
33         }
34         return [].slice.call(list, 0, i);
35     }
36
37     /**
38      * @param {ASTNode} node - a Program or BlockStatement node
39      * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body
40      */
41     function directives(node) {
42         return takeWhile(looksLikeDirective, node.body);
43     }
44
45     /**
46      * @param {ASTNode} node - any node
47      * @param {ASTNode[]} ancestors - the given node's ancestors
48      * @returns {Boolean} whether the given node is considered a directive in its current position
49      */
50     function isDirective(node, ancestors) {
51         var parent = ancestors[ancestors.length - 1],
52             grandparent = ancestors[ancestors.length - 2];
53         return (parent.type === "Program" || parent.type === "BlockStatement" &&
54                 (/Function/.test(grandparent.type))) &&
55                 directives(parent).indexOf(node) >= 0;
56     }
57
58     return {
59         "ExpressionStatement": function(node) {
60
61             var type = node.expression.type,
62                 ancestors = context.getAncestors();
63
64             if (
65                 !/^(?:Assignment|Call|New|Update|Yield)Expression$/.test(type) &&
66                 (type !== "UnaryExpression" || ["delete", "void"].indexOf(node.expression.operator) < 0) &&
67                 !isDirective(node, ancestors)
68             ) {
69                 context.report(node, "Expected an assignment or function call and instead saw an expression.");
70             }
71         }
72     };
73
74 };