2 * @fileoverview Flag expressions in statement position that do not side effect
3 * @author Michael Ficarra
4 * @copyright 2013 Michael Ficarra. All rights reserved.
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 module.exports = function(context) {
15 * @param {ASTNode} node - any node
16 * @returns {Boolean} whether the given node structurally represents a directive
18 function looksLikeDirective(node) {
19 return node.type === "ExpressionStatement" &&
20 node.expression.type === "Literal" && typeof node.expression.value === "string";
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
28 function takeWhile(predicate, list) {
29 for (var i = 0, l = list.length; i < l; ++i) {
30 if (!predicate(list[i])) {
34 return [].slice.call(list, 0, i);
38 * @param {ASTNode} node - a Program or BlockStatement node
39 * @returns {ASTNode[]} the leading sequence of directive nodes in the given node's body
41 function directives(node) {
42 return takeWhile(looksLikeDirective, node.body);
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
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;
59 "ExpressionStatement": function(node) {
61 var type = node.expression.type,
62 ancestors = context.getAncestors();
65 !/^(?:Assignment|Call|New|Update|Yield)Expression$/.test(type) &&
66 (type !== "UnaryExpression" || ["delete", "void"].indexOf(node.expression.operator) < 0) &&
67 !isDirective(node, ancestors)
69 context.report(node, "Expected an assignment or function call and instead saw an expression.");