123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- "use strict";
- const astUtils = require("./utils/ast-utils");
- module.exports = {
- meta: {
- type: "suggestion",
- docs: {
- description: "disallow comma operators",
- category: "Best Practices",
- recommended: false,
- url: "https://eslint.org/docs/rules/no-sequences"
- },
- schema: []
- },
- create(context) {
- const sourceCode = context.getSourceCode();
-
- const parenthesized = {
- DoWhileStatement: "test",
- IfStatement: "test",
- SwitchStatement: "discriminant",
- WhileStatement: "test",
- WithStatement: "object",
- ArrowFunctionExpression: "body"
-
- };
-
- function requiresExtraParens(node) {
- return node.parent && parenthesized[node.parent.type] &&
- node === node.parent[parenthesized[node.parent.type]];
- }
-
- function isParenthesised(node) {
- return astUtils.isParenthesised(sourceCode, node);
- }
-
- function isParenthesisedTwice(node) {
- const previousToken = sourceCode.getTokenBefore(node, 1),
- nextToken = sourceCode.getTokenAfter(node, 1);
- return isParenthesised(node) && previousToken && nextToken &&
- astUtils.isOpeningParenToken(previousToken) && previousToken.range[1] <= node.range[0] &&
- astUtils.isClosingParenToken(nextToken) && nextToken.range[0] >= node.range[1];
- }
- return {
- SequenceExpression(node) {
-
- if (node.parent.type === "ForStatement" &&
- (node === node.parent.init || node === node.parent.update)) {
- return;
- }
-
- if (requiresExtraParens(node)) {
- if (isParenthesisedTwice(node)) {
- return;
- }
- } else {
- if (isParenthesised(node)) {
- return;
- }
- }
- const firstCommaToken = sourceCode.getTokenAfter(node.expressions[0], astUtils.isCommaToken);
- context.report({ node, loc: firstCommaToken.loc, message: "Unexpected use of comma operator." });
- }
- };
- }
- };
|