3ece8bb065adb9ea4633824a43ea282c22703124
[platform/framework/web/crosswalk-tizen.git] /
1 /**
2  * @fileoverview Rule to enforce the number of spaces after certain keywords
3  * @author Nick Fisher
4  * @copyright 2014 Nick Fisher. All rights reserved.
5  */
6 "use strict";
7
8 //------------------------------------------------------------------------------
9 // Rule Definition
10 //------------------------------------------------------------------------------
11
12 module.exports = function(context) {
13
14     // unless the first option is `"never"`, then a space is required
15     var requiresSpace = context.options[0] !== "never";
16
17     /**
18      * Check if the separation of two adjacent tokens meets the spacing rules, and report a problem if not.
19      *
20      * @param {ASTNode} node  The node to which the potential problem belongs.
21      * @param {Token} left    The first token.
22      * @param {Token} right   The second token
23      * @returns {void}
24      */
25     function checkTokens(node, left, right) {
26         var hasSpace = left.range[1] < right.range[0],
27             value = left.value;
28
29         if (hasSpace !== requiresSpace) {
30             context.report(node, "Keyword \"{{value}}\" must {{not}}be followed by whitespace.", {
31                 value: value,
32                 not: requiresSpace ? "" : "not "
33             });
34         }
35     }
36
37     /**
38      * Check if the given node (`if`, `for`, `while`, etc), has the correct spacing after it.
39      * @param {ASTNode} node The node to check.
40      * @returns {void}
41      */
42     function check(node) {
43         var tokens = context.getFirstTokens(node, 2);
44         checkTokens(node, tokens[0], tokens[1]);
45     }
46
47     return {
48         "IfStatement": function (node) {
49             check(node);
50             // check the `else`
51             if (node.alternate && node.alternate.type !== "IfStatement") {
52                 checkTokens(node.alternate, context.getTokenBefore(node.alternate), context.getFirstToken(node.alternate));
53             }
54         },
55         "ForStatement": check,
56         "ForOfStatement": check,
57         "ForInStatement": check,
58         "WhileStatement": check,
59         "DoWhileStatement": function (node) {
60             check(node);
61             // check the `while`
62             var whileTokens = context.getTokensBefore(node.test, 2);
63             checkTokens(node, whileTokens[0], whileTokens[1]);
64         },
65         "SwitchStatement": check,
66         "TryStatement": function (node) {
67             check(node);
68             // check the `finally`
69             if (node.finalizer) {
70                 checkTokens(node.finalizer, context.getTokenBefore(node.finalizer), context.getFirstToken(node.finalizer));
71             }
72         },
73         "CatchStatement": check,
74         "WithStatement": check
75     };
76 };