4165987967f858a416e45c8e071b29d8b6fb375a
[platform/framework/web/crosswalk-tizen.git] /
1 /**
2  * @fileoverview Require spaces around infix operators
3  * @author Michael Ficarra
4  */
5 "use strict";
6
7 //------------------------------------------------------------------------------
8 // Rule Definition
9 //------------------------------------------------------------------------------
10
11 module.exports = function(context) {
12     var int32Hint = context.options[0] ? context.options[0].int32Hint === true : false;
13
14     var OPERATORS = [
15         "*", "/", "%", "+", "-", "<<", ">>", ">>>", "<", "<=", ">", ">=", "in",
16         "instanceof", "==", "!=", "===", "!==", "&", "^", "|", "&&", "||", "=",
17         "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "^=", "|=",
18         "?", ":", ","
19     ];
20
21     function isSpaced(left, right) {
22         var op, tokens = context.getTokensBetween(left, right, 1);
23         for (var i = 1, l = tokens.length - 1; i < l; ++i) {
24             op = tokens[i];
25             if (
26                 op.type === "Punctuator" &&
27                 OPERATORS.indexOf(op.value) >= 0 &&
28                 (tokens[i - 1].range[1] >= op.range[0] || op.range[1] >= tokens[i + 1].range[0])
29             ) {
30                 return false;
31             }
32         }
33         return true;
34     }
35
36     function report(node) {
37         context.report(node, "Infix operators must be spaced.");
38     }
39
40     function checkBinary(node) {
41         if (!isSpaced(node.left, node.right)) {
42             if (!(int32Hint && context.getSource(node).substr(-2) === "|0")) {
43                 report(node);
44             }
45         }
46     }
47
48     function checkConditional(node) {
49         if (!isSpaced(node.test, node.consequent) || !isSpaced(node.consequent, node.alternate)) {
50             report(node);
51         }
52     }
53
54     function checkVar(node) {
55         if (node.init && !isSpaced(node.id, node.init)) {
56             report(node);
57         }
58     }
59
60     return {
61         "AssignmentExpression": checkBinary,
62         "BinaryExpression": checkBinary,
63         "LogicalExpression": checkBinary,
64         "ConditionalExpression": checkConditional,
65         "VariableDeclarator": checkVar
66     };
67
68 };