da3776d4243dae4798dbb1333aa9f72be41e633a
[platform/framework/web/crosswalk-tizen.git] /
1 /**
2  * @fileoverview Rule to forbid or enforce dangling commas.
3  * @author Ian Christian Myers
4  * @copyright 2015 Mathias Schreck
5  * @copyright 2013 Ian Christian Myers
6  */
7
8 "use strict";
9
10 //------------------------------------------------------------------------------
11 // Rule Definition
12 //------------------------------------------------------------------------------
13
14 module.exports = function (context) {
15     var allowDangle = context.options[0];
16     var forbidDangle = allowDangle !== "always-multiline" && allowDangle !== "always";
17     var UNEXPECTED_MESSAGE = "Unexpected trailing comma.";
18     var MISSING_MESSAGE = "Missing trailing comma.";
19
20     /**
21      * Checks the given node for trailing comma and reports violations.
22      * @param {ASTNode} node The node of an ObjectExpression or ArrayExpression
23      * @returns {void}
24      */
25     function checkForTrailingComma(node) {
26         var items = node.properties || node.elements,
27             length = items.length,
28             nodeIsMultiLine = node.loc.start.line !== node.loc.end.line,
29             lastItem,
30             penultimateToken,
31             hasDanglingComma;
32
33         if (length) {
34             lastItem = items[length - 1];
35             if (lastItem) {
36                 penultimateToken = context.getLastToken(node, 1);
37                 hasDanglingComma = penultimateToken.value === ",";
38
39                 if (forbidDangle && hasDanglingComma) {
40                     context.report(lastItem, penultimateToken.loc.start, UNEXPECTED_MESSAGE);
41                 } else if (allowDangle === "always-multiline") {
42                     if (hasDanglingComma && !nodeIsMultiLine) {
43                         context.report(lastItem, penultimateToken.loc.start, UNEXPECTED_MESSAGE);
44                     } else if (!hasDanglingComma && nodeIsMultiLine) {
45                         context.report(lastItem, penultimateToken.loc.end, MISSING_MESSAGE);
46                     }
47                 } else if (allowDangle === "always" && !hasDanglingComma) {
48                     context.report(lastItem, lastItem.loc.end, MISSING_MESSAGE);
49                 }
50             }
51         }
52     }
53
54     return {
55         "ObjectExpression": checkForTrailingComma,
56         "ArrayExpression": checkForTrailingComma
57     };
58 };