2 * @fileoverview Rule to flag use of comma operator
3 * @author Brandon Mills
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 module.exports = function(context) {
15 * Parts of the grammar that are required to have parens.
18 "DoWhileStatement": "test",
19 "IfStatement": "test",
20 "SwitchStatement": "discriminant",
21 "WhileStatement": "test",
22 "WithStatement": "object"
24 // Omitting CallExpression - commas are parsed as argument separators
25 // Omitting NewExpression - commas are parsed as argument separators
26 // Omitting ForInStatement - parts aren't individually parenthesised
27 // Omitting ForStatement - parts aren't individually parenthesised
31 * Determines whether a node is required by the grammar to be wrapped in
32 * parens, e.g. the test of an if statement.
33 * @param {ASTNode} node - The AST node
34 * @returns {boolean} True if parens around node belong to parent node.
36 function requiresExtraParens(node) {
37 return node.parent && parenthesized[node.parent.type] != null &&
38 node === node.parent[parenthesized[node.parent.type]];
42 * Check if a node is wrapped in parens.
43 * @param {ASTNode} node - The AST node
44 * @returns {boolean} True if the node has a paren on each side.
46 function isParenthesised(node) {
47 var previousToken = context.getTokenBefore(node),
48 nextToken = context.getTokenAfter(node);
50 return previousToken && nextToken &&
51 previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
52 nextToken.value === ")" && nextToken.range[0] >= node.range[1];
56 * Check if a node is wrapped in two levels of parens.
57 * @param {ASTNode} node - The AST node
58 * @returns {boolean} True if two parens surround the node on each side.
60 function isParenthesisedTwice(node) {
61 var previousToken = context.getTokenBefore(node, 1),
62 nextToken = context.getTokenAfter(node, 1);
64 return isParenthesised(node) && previousToken && nextToken &&
65 previousToken.value === "(" && previousToken.range[1] <= node.range[0] &&
66 nextToken.value === ")" && nextToken.range[0] >= node.range[1];
70 "SequenceExpression": function(node) {
71 // Always allow sequences in for statement update
72 if (node.parent.type === "ForStatement" &&
73 (node === node.parent.init || node === node.parent.update)) {
77 // Wrapping a sequence in extra parens indicates intent
78 if (requiresExtraParens(node)) {
79 if (isParenthesisedTwice(node)) {
83 if (isParenthesised(node)) {
88 context.report(node, "Unexpected use of comma operator.");