2 * @fileoverview Rule to flag use of comma operator
3 * @author Brandon Mills
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const astUtils = require("./utils/ast-utils");
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
23 description: "disallow comma operators",
24 category: "Best Practices",
26 url: "https://eslint.org/docs/rules/no-sequences"
33 const sourceCode = context.getSourceCode();
36 * Parts of the grammar that are required to have parens.
38 const parenthesized = {
39 DoWhileStatement: "test",
41 SwitchStatement: "discriminant",
42 WhileStatement: "test",
43 WithStatement: "object",
44 ArrowFunctionExpression: "body"
47 * Omitting CallExpression - commas are parsed as argument separators
48 * Omitting NewExpression - commas are parsed as argument separators
49 * Omitting ForInStatement - parts aren't individually parenthesised
50 * Omitting ForStatement - parts aren't individually parenthesised
55 * Determines whether a node is required by the grammar to be wrapped in
56 * parens, e.g. the test of an if statement.
57 * @param {ASTNode} node The AST node
58 * @returns {boolean} True if parens around node belong to parent node.
60 function requiresExtraParens(node) {
61 return node.parent && parenthesized[node.parent.type] &&
62 node === node.parent[parenthesized[node.parent.type]];
66 * Check if a node is wrapped in parens.
67 * @param {ASTNode} node The AST node
68 * @returns {boolean} True if the node has a paren on each side.
70 function isParenthesised(node) {
71 return astUtils.isParenthesised(sourceCode, node);
75 * Check if a node is wrapped in two levels of parens.
76 * @param {ASTNode} node The AST node
77 * @returns {boolean} True if two parens surround the node on each side.
79 function isParenthesisedTwice(node) {
80 const previousToken = sourceCode.getTokenBefore(node, 1),
81 nextToken = sourceCode.getTokenAfter(node, 1);
83 return isParenthesised(node) && previousToken && nextToken &&
84 astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] &&
85 astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1];
89 SequenceExpression(node) {
91 // Always allow sequences in for statement update
92 if (node.parent.type === "ForStatement" &&
93 (node === node.parent.init || node === node.parent.update)) {
97 // Wrapping a sequence in extra parens indicates intent
98 if (requiresExtraParens(node)) {
99 if (isParenthesisedTwice(node)) {
103 if (isParenthesised(node)) {
108 const firstCommaToken = sourceCode.getTokenAfter(node.expressions[0], astUtils.isCommaToken);
110 context.report({ node, loc: firstCommaToken.loc, message: "Unexpected use of comma operator." });