2 * @fileoverview Disallow parenthesising higher precedence subexpressions.
3 * @author Michael Ficarra
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const { isParenthesized: isParenthesizedRaw } = require("eslint-utils");
12 const astUtils = require("./utils/ast-utils.js");
19 description: "disallow unnecessary parentheses",
20 category: "Possible Errors",
22 url: "https://eslint.org/docs/rules/no-extra-parens"
48 conditionalAssign: { type: "boolean" },
49 nestedBinaryExpressions: { type: "boolean" },
50 returnAssign: { type: "boolean" },
51 ignoreJSX: { enum: ["none", "all", "single-line", "multi-line"] },
52 enforceForArrowConditionals: { type: "boolean" },
53 enforceForSequenceExpressions: { type: "boolean" },
54 enforceForNewInMemberExpressions: { type: "boolean" },
55 enforceForFunctionPrototypeMethods: { type: "boolean" }
57 additionalProperties: false
67 unexpected: "Unnecessary parentheses around expression."
72 const sourceCode = context.getSourceCode();
74 const tokensToIgnore = new WeakSet();
75 const precedence = astUtils.getPrecedence;
76 const ALL_NODES = context.options[0] !== "functions";
77 const EXCEPT_COND_ASSIGN = ALL_NODES && context.options[1] && context.options[1].conditionalAssign === false;
78 const NESTED_BINARY = ALL_NODES && context.options[1] && context.options[1].nestedBinaryExpressions === false;
79 const EXCEPT_RETURN_ASSIGN = ALL_NODES && context.options[1] && context.options[1].returnAssign === false;
80 const IGNORE_JSX = ALL_NODES && context.options[1] && context.options[1].ignoreJSX;
81 const IGNORE_ARROW_CONDITIONALS = ALL_NODES && context.options[1] &&
82 context.options[1].enforceForArrowConditionals === false;
83 const IGNORE_SEQUENCE_EXPRESSIONS = ALL_NODES && context.options[1] &&
84 context.options[1].enforceForSequenceExpressions === false;
85 const IGNORE_NEW_IN_MEMBER_EXPR = ALL_NODES && context.options[1] &&
86 context.options[1].enforceForNewInMemberExpressions === false;
87 const IGNORE_FUNCTION_PROTOTYPE_METHODS = ALL_NODES && context.options[1] &&
88 context.options[1].enforceForFunctionPrototypeMethods === false;
90 const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({ type: "AssignmentExpression" });
91 const PRECEDENCE_OF_UPDATE_EXPR = precedence({ type: "UpdateExpression" });
96 * Determines whether the given node is a `call` or `apply` method call, invoked directly on a `FunctionExpression` node.
97 * Example: function(){}.call()
98 * @param {ASTNode} node The node to be checked.
99 * @returns {boolean} True if the node is an immediate `call` or `apply` method call.
102 function isImmediateFunctionPrototypeMethodCall(node) {
103 const callNode = astUtils.skipChainExpression(node);
105 if (callNode.type !== "CallExpression") {
108 const callee = astUtils.skipChainExpression(callNode.callee);
111 callee.type === "MemberExpression" &&
112 callee.object.type === "FunctionExpression" &&
113 ["call", "apply"].includes(astUtils.getStaticPropertyName(callee))
118 * Determines if this rule should be enforced for a node given the current configuration.
119 * @param {ASTNode} node The node to be checked.
120 * @returns {boolean} True if the rule should be enforced for this node.
123 function ruleApplies(node) {
124 if (node.type === "JSXElement" || node.type === "JSXFragment") {
125 const isSingleLine = node.loc.start.line === node.loc.end.line;
127 switch (IGNORE_JSX) {
129 // Exclude this JSX element from linting
133 // Exclude this JSX element if it is multi-line element
137 // Exclude this JSX element if it is single-line element
139 return !isSingleLine;
141 // Nothing special to be done for JSX elements
149 if (node.type === "SequenceExpression" && IGNORE_SEQUENCE_EXPRESSIONS) {
153 if (isImmediateFunctionPrototypeMethodCall(node) && IGNORE_FUNCTION_PROTOTYPE_METHODS) {
157 return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
161 * Determines if a node is surrounded by parentheses.
162 * @param {ASTNode} node The node to be checked.
163 * @returns {boolean} True if the node is parenthesised.
166 function isParenthesised(node) {
167 return isParenthesizedRaw(1, node, sourceCode);
171 * Determines if a node is surrounded by parentheses twice.
172 * @param {ASTNode} node The node to be checked.
173 * @returns {boolean} True if the node is doubly parenthesised.
176 function isParenthesisedTwice(node) {
177 return isParenthesizedRaw(2, node, sourceCode);
181 * Determines if a node is surrounded by (potentially) invalid parentheses.
182 * @param {ASTNode} node The node to be checked.
183 * @returns {boolean} True if the node is incorrectly parenthesised.
186 function hasExcessParens(node) {
187 return ruleApplies(node) && isParenthesised(node);
191 * Determines if a node that is expected to be parenthesised is surrounded by
192 * (potentially) invalid extra parentheses.
193 * @param {ASTNode} node The node to be checked.
194 * @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
197 function hasDoubleExcessParens(node) {
198 return ruleApplies(node) && isParenthesisedTwice(node);
202 * Determines if a node that is expected to be parenthesised is surrounded by
203 * (potentially) invalid extra parentheses with considering precedence level of the node.
204 * If the preference level of the node is not higher or equal to precedence lower limit, it also checks
205 * whether the node is surrounded by parentheses twice or not.
206 * @param {ASTNode} node The node to be checked.
207 * @param {number} precedenceLowerLimit The lower limit of precedence.
208 * @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
211 function hasExcessParensWithPrecedence(node, precedenceLowerLimit) {
212 if (ruleApplies(node) && isParenthesised(node)) {
214 precedence(node) >= precedenceLowerLimit ||
215 isParenthesisedTwice(node)
224 * Determines if a node test expression is allowed to have a parenthesised assignment
225 * @param {ASTNode} node The node to be checked.
226 * @returns {boolean} True if the assignment can be parenthesised.
229 function isCondAssignException(node) {
230 return EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression";
234 * Determines if a node is in a return statement
235 * @param {ASTNode} node The node to be checked.
236 * @returns {boolean} True if the node is in a return statement.
239 function isInReturnStatement(node) {
240 for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
242 currentNode.type === "ReturnStatement" ||
243 (currentNode.type === "ArrowFunctionExpression" && currentNode.body.type !== "BlockStatement")
253 * Determines if a constructor function is newed-up with parens
254 * @param {ASTNode} newExpression The NewExpression node to be checked.
255 * @returns {boolean} True if the constructor is called with parens.
258 function isNewExpressionWithParens(newExpression) {
259 const lastToken = sourceCode.getLastToken(newExpression);
260 const penultimateToken = sourceCode.getTokenBefore(lastToken);
262 return newExpression.arguments.length > 0 ||
265 // The expression should end with its own parens, e.g., new new foo() is not a new expression with parens
266 astUtils.isOpeningParenToken(penultimateToken) &&
267 astUtils.isClosingParenToken(lastToken) &&
268 newExpression.callee.range[1] < newExpression.range[1]
273 * Determines if a node is or contains an assignment expression
274 * @param {ASTNode} node The node to be checked.
275 * @returns {boolean} True if the node is or contains an assignment expression.
278 function containsAssignment(node) {
279 if (node.type === "AssignmentExpression") {
282 if (node.type === "ConditionalExpression" &&
283 (node.consequent.type === "AssignmentExpression" || node.alternate.type === "AssignmentExpression")) {
286 if ((node.left && node.left.type === "AssignmentExpression") ||
287 (node.right && node.right.type === "AssignmentExpression")) {
295 * Determines if a node is contained by or is itself a return statement and is allowed to have a parenthesised assignment
296 * @param {ASTNode} node The node to be checked.
297 * @returns {boolean} True if the assignment can be parenthesised.
300 function isReturnAssignException(node) {
301 if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) {
305 if (node.type === "ReturnStatement") {
306 return node.argument && containsAssignment(node.argument);
308 if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
309 return containsAssignment(node.body);
311 return containsAssignment(node);
316 * Determines if a node following a [no LineTerminator here] restriction is
317 * surrounded by (potentially) invalid extra parentheses.
318 * @param {Token} token The token preceding the [no LineTerminator here] restriction.
319 * @param {ASTNode} node The node to be checked.
320 * @returns {boolean} True if the node is incorrectly parenthesised.
323 function hasExcessParensNoLineTerminator(token, node) {
324 if (token.loc.end.line === node.loc.start.line) {
325 return hasExcessParens(node);
328 return hasDoubleExcessParens(node);
332 * Determines whether a node should be preceded by an additional space when removing parens
333 * @param {ASTNode} node node to evaluate; must be surrounded by parentheses
334 * @returns {boolean} `true` if a space should be inserted before the node
337 function requiresLeadingSpace(node) {
338 const leftParenToken = sourceCode.getTokenBefore(node);
339 const tokenBeforeLeftParen = sourceCode.getTokenBefore(leftParenToken, { includeComments: true });
340 const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParenToken, { includeComments: true });
342 return tokenBeforeLeftParen &&
343 tokenBeforeLeftParen.range[1] === leftParenToken.range[0] &&
344 leftParenToken.range[1] === tokenAfterLeftParen.range[0] &&
345 !astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, tokenAfterLeftParen);
349 * Determines whether a node should be followed by an additional space when removing parens
350 * @param {ASTNode} node node to evaluate; must be surrounded by parentheses
351 * @returns {boolean} `true` if a space should be inserted after the node
354 function requiresTrailingSpace(node) {
355 const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 });
356 const rightParenToken = nextTwoTokens[0];
357 const tokenAfterRightParen = nextTwoTokens[1];
358 const tokenBeforeRightParen = sourceCode.getLastToken(node);
360 return rightParenToken && tokenAfterRightParen &&
361 !sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) &&
362 !astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen);
366 * Determines if a given expression node is an IIFE
367 * @param {ASTNode} node The node to check
368 * @returns {boolean} `true` if the given node is an IIFE
370 function isIIFE(node) {
371 const maybeCallNode = astUtils.skipChainExpression(node);
373 return maybeCallNode.type === "CallExpression" && maybeCallNode.callee.type === "FunctionExpression";
377 * Determines if the given node can be the assignment target in destructuring or the LHS of an assignment.
378 * This is to avoid an autofix that could change behavior because parsers mistakenly allow invalid syntax,
379 * such as `(a = b) = c` and `[(a = b) = c] = []`. Ideally, this function shouldn't be necessary.
380 * @param {ASTNode} [node] The node to check
381 * @returns {boolean} `true` if the given node can be a valid assignment target
383 function canBeAssignmentTarget(node) {
384 return node && (node.type === "Identifier" || node.type === "MemberExpression");
389 * @param {ASTNode} node node to evaluate
393 function report(node) {
394 const leftParenToken = sourceCode.getTokenBefore(node);
395 const rightParenToken = sourceCode.getTokenAfter(node);
397 if (!isParenthesisedTwice(node)) {
398 if (tokensToIgnore.has(sourceCode.getFirstToken(node))) {
402 if (isIIFE(node) && !isParenthesised(node.callee)) {
412 function finishReport() {
415 loc: leftParenToken.loc,
416 messageId: "unexpected",
418 const parenthesizedSource = sourceCode.text.slice(leftParenToken.range[1], rightParenToken.range[0]);
420 return fixer.replaceTextRange([
421 leftParenToken.range[0],
422 rightParenToken.range[1]
423 ], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource + (requiresTrailingSpace(node) ? " " : ""));
429 reportsBuffer.reports.push({ node, finishReport });
437 * Evaluate a argument of the node.
438 * @param {ASTNode} node node to evaluate
442 function checkArgumentWithPrecedence(node) {
443 if (hasExcessParensWithPrecedence(node.argument, precedence(node))) {
444 report(node.argument);
449 * Check if a member expression contains a call expression
450 * @param {ASTNode} node MemberExpression node to evaluate
451 * @returns {boolean} true if found, false if not
453 function doesMemberExpressionContainCallExpression(node) {
454 let currentNode = node.object;
455 let currentNodeType = node.object.type;
457 while (currentNodeType === "MemberExpression") {
458 currentNode = currentNode.object;
459 currentNodeType = currentNode.type;
462 return currentNodeType === "CallExpression";
466 * Evaluate a new call
467 * @param {ASTNode} node node to evaluate
471 function checkCallNew(node) {
472 const callee = node.callee;
474 if (hasExcessParensWithPrecedence(callee, precedence(node))) {
476 hasDoubleExcessParens(callee) ||
480 // (new A)(); new (new A)();
482 callee.type === "NewExpression" &&
483 !isNewExpressionWithParens(callee) &&
485 node.type === "NewExpression" &&
486 !isNewExpressionWithParens(node)
490 // new (a().b)(); new (a.b().c);
492 node.type === "NewExpression" &&
493 callee.type === "MemberExpression" &&
494 doesMemberExpressionContainCallExpression(callee)
497 // (a?.b)(); (a?.())();
500 callee.type === "ChainExpression"
508 .filter(arg => hasExcessParensWithPrecedence(arg, PRECEDENCE_OF_ASSIGNMENT_EXPR))
513 * Evaluate binary logicals
514 * @param {ASTNode} node node to evaluate
518 function checkBinaryLogical(node) {
519 const prec = precedence(node);
520 const leftPrecedence = precedence(node.left);
521 const rightPrecedence = precedence(node.right);
522 const isExponentiation = node.operator === "**";
523 const shouldSkipLeft = NESTED_BINARY && (node.left.type === "BinaryExpression" || node.left.type === "LogicalExpression");
524 const shouldSkipRight = NESTED_BINARY && (node.right.type === "BinaryExpression" || node.right.type === "LogicalExpression");
526 if (!shouldSkipLeft && hasExcessParens(node.left)) {
528 !(["AwaitExpression", "UnaryExpression"].includes(node.left.type) && isExponentiation) &&
529 !astUtils.isMixedLogicalAndCoalesceExpressions(node.left, node) &&
530 (leftPrecedence > prec || (leftPrecedence === prec && !isExponentiation)) ||
531 isParenthesisedTwice(node.left)
537 if (!shouldSkipRight && hasExcessParens(node.right)) {
539 !astUtils.isMixedLogicalAndCoalesceExpressions(node.right, node) &&
540 (rightPrecedence > prec || (rightPrecedence === prec && isExponentiation)) ||
541 isParenthesisedTwice(node.right)
549 * Check the parentheses around the super class of the given class definition.
550 * @param {ASTNode} node The node of class declarations to check.
553 function checkClass(node) {
554 if (!node.superClass) {
559 * If `node.superClass` is a LeftHandSideExpression, parentheses are extra.
560 * Otherwise, parentheses are needed.
562 const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR
563 ? hasExcessParens(node.superClass)
564 : hasDoubleExcessParens(node.superClass);
566 if (hasExtraParens) {
567 report(node.superClass);
572 * Check the parentheses around the argument of the given spread operator.
573 * @param {ASTNode} node The node of spread elements/properties to check.
576 function checkSpreadOperator(node) {
577 if (hasExcessParensWithPrecedence(node.argument, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
578 report(node.argument);
583 * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration
584 * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node
587 function checkExpressionOrExportStatement(node) {
588 const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node);
589 const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken);
590 const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null;
591 const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null;
594 astUtils.isOpeningParenToken(firstToken) &&
596 astUtils.isOpeningBraceToken(secondToken) ||
597 secondToken.type === "Keyword" && (
598 secondToken.value === "function" ||
599 secondToken.value === "class" ||
600 secondToken.value === "let" &&
601 tokenAfterClosingParens &&
603 astUtils.isOpeningBracketToken(tokenAfterClosingParens) ||
604 tokenAfterClosingParens.type === "Identifier"
607 secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function"
610 tokensToIgnore.add(secondToken);
613 const hasExtraParens = node.parent.type === "ExportDefaultDeclaration"
614 ? hasExcessParensWithPrecedence(node, PRECEDENCE_OF_ASSIGNMENT_EXPR)
615 : hasExcessParens(node);
617 if (hasExtraParens) {
623 * Finds the path from the given node to the specified ancestor.
624 * @param {ASTNode} node First node in the path.
625 * @param {ASTNode} ancestor Last node in the path.
626 * @returns {ASTNode[]} Path, including both nodes.
627 * @throws {Error} If the given node does not have the specified ancestor.
629 function pathToAncestor(node, ancestor) {
631 let currentNode = node;
633 while (currentNode !== ancestor) {
635 currentNode = currentNode.parent;
637 /* istanbul ignore if */
638 if (currentNode === null) {
639 throw new Error("Nodes are not in the ancestor-descendant relationship.");
642 path.push(currentNode);
649 * Finds the path from the given node to the specified descendant.
650 * @param {ASTNode} node First node in the path.
651 * @param {ASTNode} descendant Last node in the path.
652 * @returns {ASTNode[]} Path, including both nodes.
653 * @throws {Error} If the given node does not have the specified descendant.
655 function pathToDescendant(node, descendant) {
656 return pathToAncestor(descendant, node).reverse();
660 * Checks whether the syntax of the given ancestor of an 'in' expression inside a for-loop initializer
661 * is preventing the 'in' keyword from being interpreted as a part of an ill-formed for-in loop.
662 * @param {ASTNode} node Ancestor of an 'in' expression.
663 * @param {ASTNode} child Child of the node, ancestor of the same 'in' expression or the 'in' expression itself.
664 * @returns {boolean} True if the keyword 'in' would be interpreted as the 'in' operator, without any parenthesis.
666 function isSafelyEnclosingInExpression(node, child) {
668 case "ArrayExpression":
670 case "BlockStatement":
671 case "ObjectExpression":
672 case "ObjectPattern":
673 case "TemplateLiteral":
675 case "ArrowFunctionExpression":
676 case "FunctionExpression":
677 return node.params.includes(child);
678 case "CallExpression":
679 case "NewExpression":
680 return node.arguments.includes(child);
681 case "MemberExpression":
682 return node.computed && node.property === child;
683 case "ConditionalExpression":
684 return node.consequent === child;
691 * Starts a new reports buffering. Warnings will be stored in a buffer instead of being reported immediately.
692 * An additional logic that requires multiple nodes (e.g. a whole subtree) may dismiss some of the stored warnings.
695 function startNewReportsBuffering() {
697 upper: reportsBuffer,
698 inExpressionNodes: [],
704 * Ends the current reports buffering.
707 function endCurrentReportsBuffering() {
708 const { upper, inExpressionNodes, reports } = reportsBuffer;
711 upper.inExpressionNodes.push(...inExpressionNodes);
712 upper.reports.push(...reports);
715 // flush remaining reports
716 reports.forEach(({ finishReport }) => finishReport());
719 reportsBuffer = upper;
723 * Checks whether the given node is in the current reports buffer.
724 * @param {ASTNode} node Node to check.
725 * @returns {boolean} True if the node is in the current buffer, false otherwise.
727 function isInCurrentReportsBuffer(node) {
728 return reportsBuffer.reports.some(r => r.node === node);
732 * Removes the given node from the current reports buffer.
733 * @param {ASTNode} node Node to remove.
736 function removeFromCurrentReportsBuffer(node) {
737 reportsBuffer.reports = reportsBuffer.reports.filter(r => r.node !== node);
741 * Checks whether a node is a MemberExpression at NewExpression's callee.
742 * @param {ASTNode} node node to check.
743 * @returns {boolean} True if the node is a MemberExpression at NewExpression's callee. false otherwise.
745 function isMemberExpInNewCallee(node) {
746 if (node.type === "MemberExpression") {
747 return node.parent.type === "NewExpression" && node.parent.callee === node
749 : node.parent.object === node && isMemberExpInNewCallee(node.parent);
755 ArrayExpression(node) {
757 .filter(e => e && hasExcessParensWithPrecedence(e, PRECEDENCE_OF_ASSIGNMENT_EXPR))
763 .filter(e => canBeAssignmentTarget(e) && hasExcessParens(e))
767 ArrowFunctionExpression(node) {
768 if (isReturnAssignException(node)) {
772 if (node.body.type === "ConditionalExpression" &&
773 IGNORE_ARROW_CONDITIONALS
778 if (node.body.type !== "BlockStatement") {
779 const firstBodyToken = sourceCode.getFirstToken(node.body, astUtils.isNotOpeningParenToken);
780 const tokenBeforeFirst = sourceCode.getTokenBefore(firstBodyToken);
782 if (astUtils.isOpeningParenToken(tokenBeforeFirst) && astUtils.isOpeningBraceToken(firstBodyToken)) {
783 tokensToIgnore.add(firstBodyToken);
785 if (hasExcessParensWithPrecedence(node.body, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
791 AssignmentExpression(node) {
792 if (canBeAssignmentTarget(node.left) && hasExcessParens(node.left)) {
796 if (!isReturnAssignException(node) && hasExcessParensWithPrecedence(node.right, precedence(node))) {
801 BinaryExpression(node) {
802 if (reportsBuffer && node.operator === "in") {
803 reportsBuffer.inExpressionNodes.push(node);
806 checkBinaryLogical(node);
809 CallExpression: checkCallNew,
813 .filter(member => member.type === "MethodDefinition" && member.computed && member.key)
814 .filter(member => hasExcessParensWithPrecedence(member.key, PRECEDENCE_OF_ASSIGNMENT_EXPR))
815 .forEach(member => report(member.key));
818 ConditionalExpression(node) {
819 if (isReturnAssignException(node)) {
823 !isCondAssignException(node) &&
824 hasExcessParensWithPrecedence(node.test, precedence({ type: "LogicalExpression", operator: "||" }))
829 if (hasExcessParensWithPrecedence(node.consequent, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
830 report(node.consequent);
833 if (hasExcessParensWithPrecedence(node.alternate, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
834 report(node.alternate);
838 DoWhileStatement(node) {
839 if (hasExcessParens(node.test) && !isCondAssignException(node)) {
844 ExportDefaultDeclaration: node => checkExpressionOrExportStatement(node.declaration),
845 ExpressionStatement: node => checkExpressionOrExportStatement(node.expression),
847 ForInStatement(node) {
848 if (node.left.type !== "VariableDeclaration") {
849 const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken);
852 firstLeftToken.value === "let" &&
853 astUtils.isOpeningBracketToken(
854 sourceCode.getTokenAfter(firstLeftToken, astUtils.isNotClosingParenToken)
858 // ForInStatement#left expression cannot start with `let[`.
859 tokensToIgnore.add(firstLeftToken);
863 if (hasExcessParens(node.left)) {
867 if (hasExcessParens(node.right)) {
872 ForOfStatement(node) {
873 if (node.left.type !== "VariableDeclaration") {
874 const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken);
876 if (firstLeftToken.value === "let") {
878 // ForOfStatement#left expression cannot start with `let`.
879 tokensToIgnore.add(firstLeftToken);
883 if (hasExcessParens(node.left)) {
887 if (hasExcessParensWithPrecedence(node.right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
893 if (node.test && hasExcessParens(node.test) && !isCondAssignException(node)) {
897 if (node.update && hasExcessParens(node.update)) {
903 if (node.init.type !== "VariableDeclaration") {
904 const firstToken = sourceCode.getFirstToken(node.init, astUtils.isNotOpeningParenToken);
907 firstToken.value === "let" &&
908 astUtils.isOpeningBracketToken(
909 sourceCode.getTokenAfter(firstToken, astUtils.isNotClosingParenToken)
913 // ForStatement#init expression cannot start with `let[`.
914 tokensToIgnore.add(firstToken);
918 startNewReportsBuffering();
920 if (hasExcessParens(node.init)) {
926 "ForStatement > *.init:exit"(node) {
929 * Removing parentheses around `in` expressions might change semantics and cause errors.
931 * For example, this valid for loop:
932 * for (let a = (b in c); ;);
933 * after removing parentheses would be treated as an invalid for-in loop:
934 * for (let a = b in c; ;);
937 if (reportsBuffer.reports.length) {
938 reportsBuffer.inExpressionNodes.forEach(inExpressionNode => {
939 const path = pathToDescendant(node, inExpressionNode);
942 for (let i = 0; i < path.length; i++) {
943 const pathNode = path[i];
945 if (i < path.length - 1) {
946 const nextPathNode = path[i + 1];
948 if (isSafelyEnclosingInExpression(pathNode, nextPathNode)) {
950 // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]').
955 if (isParenthesised(pathNode)) {
956 if (isInCurrentReportsBuffer(pathNode)) {
958 // This node was supposed to be reported, but parentheses might be necessary.
960 if (isParenthesisedTwice(pathNode)) {
963 * This node is parenthesised twice, it certainly has at least one pair of `extra` parentheses.
964 * If the --fix option is on, the current fixing iteration will remove only one pair of parentheses.
965 * The remaining pair is safely enclosing the 'in' expression.
970 // Exclude the outermost node only.
971 if (!nodeToExclude) {
972 nodeToExclude = pathNode;
975 // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside.
979 // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'.
985 // Exclude the node from the list (i.e. treat parentheses as necessary)
986 removeFromCurrentReportsBuffer(nodeToExclude);
990 endCurrentReportsBuffering();
994 if (hasExcessParens(node.test) && !isCondAssignException(node)) {
999 ImportExpression(node) {
1000 const { source } = node;
1002 if (source.type === "SequenceExpression") {
1003 if (hasDoubleExcessParens(source)) {
1006 } else if (hasExcessParens(source)) {
1011 LogicalExpression: checkBinaryLogical,
1013 MemberExpression(node) {
1014 const shouldAllowWrapOnce = isMemberExpInNewCallee(node) &&
1015 doesMemberExpressionContainCallExpression(node);
1016 const nodeObjHasExcessParens = shouldAllowWrapOnce
1017 ? hasDoubleExcessParens(node.object)
1018 : hasExcessParens(node.object) &&
1020 isImmediateFunctionPrototypeMethodCall(node.parent) &&
1021 node.parent.callee === node &&
1022 IGNORE_FUNCTION_PROTOTYPE_METHODS
1026 nodeObjHasExcessParens &&
1027 precedence(node.object) >= precedence(node) &&
1031 astUtils.isDecimalInteger(node.object) ||
1033 // RegExp literal is allowed to have parens (#1589)
1034 (node.object.type === "Literal" && node.object.regex)
1038 report(node.object);
1041 if (nodeObjHasExcessParens &&
1042 node.object.type === "CallExpression"
1044 report(node.object);
1047 if (nodeObjHasExcessParens &&
1048 !IGNORE_NEW_IN_MEMBER_EXPR &&
1049 node.object.type === "NewExpression" &&
1050 isNewExpressionWithParens(node.object)) {
1051 report(node.object);
1054 if (nodeObjHasExcessParens &&
1056 node.object.type === "ChainExpression"
1058 report(node.object);
1061 if (node.computed && hasExcessParens(node.property)) {
1062 report(node.property);
1066 NewExpression: checkCallNew,
1068 ObjectExpression(node) {
1070 .filter(property => property.value && hasExcessParensWithPrecedence(property.value, PRECEDENCE_OF_ASSIGNMENT_EXPR))
1071 .forEach(property => report(property.value));
1074 ObjectPattern(node) {
1076 .filter(property => {
1077 const value = property.value;
1079 return canBeAssignmentTarget(value) && hasExcessParens(value);
1080 }).forEach(property => report(property.value));
1084 if (node.computed) {
1085 const { key } = node;
1087 if (key && hasExcessParensWithPrecedence(key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
1094 const argument = node.argument;
1096 if (canBeAssignmentTarget(argument) && hasExcessParens(argument)) {
1101 ReturnStatement(node) {
1102 const returnToken = sourceCode.getFirstToken(node);
1104 if (isReturnAssignException(node)) {
1108 if (node.argument &&
1109 hasExcessParensNoLineTerminator(returnToken, node.argument) &&
1111 // RegExp literal is allowed to have parens (#1589)
1112 !(node.argument.type === "Literal" && node.argument.regex)) {
1113 report(node.argument);
1117 SequenceExpression(node) {
1118 const precedenceOfNode = precedence(node);
1121 .filter(e => hasExcessParensWithPrecedence(e, precedenceOfNode))
1126 if (node.test && hasExcessParens(node.test)) {
1131 SwitchStatement(node) {
1132 if (hasExcessParens(node.discriminant)) {
1133 report(node.discriminant);
1137 ThrowStatement(node) {
1138 const throwToken = sourceCode.getFirstToken(node);
1140 if (hasExcessParensNoLineTerminator(throwToken, node.argument)) {
1141 report(node.argument);
1145 UnaryExpression: checkArgumentWithPrecedence,
1146 UpdateExpression(node) {
1148 checkArgumentWithPrecedence(node);
1150 const { argument } = node;
1151 const operatorToken = sourceCode.getLastToken(node);
1153 if (argument.loc.end.line === operatorToken.loc.start.line) {
1154 checkArgumentWithPrecedence(node);
1156 if (hasDoubleExcessParens(argument)) {
1162 AwaitExpression: checkArgumentWithPrecedence,
1164 VariableDeclarator(node) {
1166 node.init && hasExcessParensWithPrecedence(node.init, PRECEDENCE_OF_ASSIGNMENT_EXPR) &&
1168 // RegExp literal is allowed to have parens (#1589)
1169 !(node.init.type === "Literal" && node.init.regex)
1175 WhileStatement(node) {
1176 if (hasExcessParens(node.test) && !isCondAssignException(node)) {
1181 WithStatement(node) {
1182 if (hasExcessParens(node.object)) {
1183 report(node.object);
1187 YieldExpression(node) {
1188 if (node.argument) {
1189 const yieldToken = sourceCode.getFirstToken(node);
1191 if ((precedence(node.argument) >= precedence(node) &&
1192 hasExcessParensNoLineTerminator(yieldToken, node.argument)) ||
1193 hasDoubleExcessParens(node.argument)) {
1194 report(node.argument);
1199 ClassDeclaration: checkClass,
1200 ClassExpression: checkClass,
1202 SpreadElement: checkSpreadOperator,
1203 SpreadProperty: checkSpreadOperator,
1204 ExperimentalSpreadProperty: checkSpreadOperator,
1206 TemplateLiteral(node) {
1208 .filter(e => e && hasExcessParens(e))
1212 AssignmentPattern(node) {
1213 const { left, right } = node;
1215 if (canBeAssignmentTarget(left) && hasExcessParens(left)) {
1219 if (right && hasExcessParensWithPrecedence(right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {