UNPKG

48.3 kBJavaScriptView Raw
1/**
2 * @fileoverview Disallow parenthesising higher precedence subexpressions.
3 * @author Michael Ficarra
4 */
5"use strict";
6
7//------------------------------------------------------------------------------
8// Rule Definition
9//------------------------------------------------------------------------------
10
11const { isParenthesized: isParenthesizedRaw } = require("eslint-utils");
12const astUtils = require("./utils/ast-utils.js");
13
14module.exports = {
15 meta: {
16 type: "layout",
17
18 docs: {
19 description: "disallow unnecessary parentheses",
20 category: "Possible Errors",
21 recommended: false,
22 url: "https://eslint.org/docs/rules/no-extra-parens"
23 },
24
25 fixable: "code",
26
27 schema: {
28 anyOf: [
29 {
30 type: "array",
31 items: [
32 {
33 enum: ["functions"]
34 }
35 ],
36 minItems: 0,
37 maxItems: 1
38 },
39 {
40 type: "array",
41 items: [
42 {
43 enum: ["all"]
44 },
45 {
46 type: "object",
47 properties: {
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" }
56 },
57 additionalProperties: false
58 }
59 ],
60 minItems: 0,
61 maxItems: 2
62 }
63 ]
64 },
65
66 messages: {
67 unexpected: "Unnecessary parentheses around expression."
68 }
69 },
70
71 create(context) {
72 const sourceCode = context.getSourceCode();
73
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;
89
90 const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({ type: "AssignmentExpression" });
91 const PRECEDENCE_OF_UPDATE_EXPR = precedence({ type: "UpdateExpression" });
92
93 let reportsBuffer;
94
95 /**
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.
100 * @private
101 */
102 function isImmediateFunctionPrototypeMethodCall(node) {
103 const callNode = astUtils.skipChainExpression(node);
104
105 if (callNode.type !== "CallExpression") {
106 return false;
107 }
108 const callee = astUtils.skipChainExpression(callNode.callee);
109
110 return (
111 callee.type === "MemberExpression" &&
112 callee.object.type === "FunctionExpression" &&
113 ["call", "apply"].includes(astUtils.getStaticPropertyName(callee))
114 );
115 }
116
117 /**
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.
121 * @private
122 */
123 function ruleApplies(node) {
124 if (node.type === "JSXElement" || node.type === "JSXFragment") {
125 const isSingleLine = node.loc.start.line === node.loc.end.line;
126
127 switch (IGNORE_JSX) {
128
129 // Exclude this JSX element from linting
130 case "all":
131 return false;
132
133 // Exclude this JSX element if it is multi-line element
134 case "multi-line":
135 return isSingleLine;
136
137 // Exclude this JSX element if it is single-line element
138 case "single-line":
139 return !isSingleLine;
140
141 // Nothing special to be done for JSX elements
142 case "none":
143 break;
144
145 // no default
146 }
147 }
148
149 if (node.type === "SequenceExpression" && IGNORE_SEQUENCE_EXPRESSIONS) {
150 return false;
151 }
152
153 if (isImmediateFunctionPrototypeMethodCall(node) && IGNORE_FUNCTION_PROTOTYPE_METHODS) {
154 return false;
155 }
156
157 return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
158 }
159
160 /**
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.
164 * @private
165 */
166 function isParenthesised(node) {
167 return isParenthesizedRaw(1, node, sourceCode);
168 }
169
170 /**
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.
174 * @private
175 */
176 function isParenthesisedTwice(node) {
177 return isParenthesizedRaw(2, node, sourceCode);
178 }
179
180 /**
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.
184 * @private
185 */
186 function hasExcessParens(node) {
187 return ruleApplies(node) && isParenthesised(node);
188 }
189
190 /**
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.
195 * @private
196 */
197 function hasDoubleExcessParens(node) {
198 return ruleApplies(node) && isParenthesisedTwice(node);
199 }
200
201 /**
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.
209 * @private
210 */
211 function hasExcessParensWithPrecedence(node, precedenceLowerLimit) {
212 if (ruleApplies(node) && isParenthesised(node)) {
213 if (
214 precedence(node) >= precedenceLowerLimit ||
215 isParenthesisedTwice(node)
216 ) {
217 return true;
218 }
219 }
220 return false;
221 }
222
223 /**
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.
227 * @private
228 */
229 function isCondAssignException(node) {
230 return EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression";
231 }
232
233 /**
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.
237 * @private
238 */
239 function isInReturnStatement(node) {
240 for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
241 if (
242 currentNode.type === "ReturnStatement" ||
243 (currentNode.type === "ArrowFunctionExpression" && currentNode.body.type !== "BlockStatement")
244 ) {
245 return true;
246 }
247 }
248
249 return false;
250 }
251
252 /**
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.
256 * @private
257 */
258 function isNewExpressionWithParens(newExpression) {
259 const lastToken = sourceCode.getLastToken(newExpression);
260 const penultimateToken = sourceCode.getTokenBefore(lastToken);
261
262 return newExpression.arguments.length > 0 ||
263 (
264
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]
269 );
270 }
271
272 /**
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.
276 * @private
277 */
278 function containsAssignment(node) {
279 if (node.type === "AssignmentExpression") {
280 return true;
281 }
282 if (node.type === "ConditionalExpression" &&
283 (node.consequent.type === "AssignmentExpression" || node.alternate.type === "AssignmentExpression")) {
284 return true;
285 }
286 if ((node.left && node.left.type === "AssignmentExpression") ||
287 (node.right && node.right.type === "AssignmentExpression")) {
288 return true;
289 }
290
291 return false;
292 }
293
294 /**
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.
298 * @private
299 */
300 function isReturnAssignException(node) {
301 if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) {
302 return false;
303 }
304
305 if (node.type === "ReturnStatement") {
306 return node.argument && containsAssignment(node.argument);
307 }
308 if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
309 return containsAssignment(node.body);
310 }
311 return containsAssignment(node);
312
313 }
314
315 /**
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.
321 * @private
322 */
323 function hasExcessParensNoLineTerminator(token, node) {
324 if (token.loc.end.line === node.loc.start.line) {
325 return hasExcessParens(node);
326 }
327
328 return hasDoubleExcessParens(node);
329 }
330
331 /**
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
335 * @private
336 */
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 });
341
342 return tokenBeforeLeftParen &&
343 tokenBeforeLeftParen.range[1] === leftParenToken.range[0] &&
344 leftParenToken.range[1] === tokenAfterLeftParen.range[0] &&
345 !astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, tokenAfterLeftParen);
346 }
347
348 /**
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
352 * @private
353 */
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);
359
360 return rightParenToken && tokenAfterRightParen &&
361 !sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) &&
362 !astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen);
363 }
364
365 /**
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
369 */
370 function isIIFE(node) {
371 const maybeCallNode = astUtils.skipChainExpression(node);
372
373 return maybeCallNode.type === "CallExpression" && maybeCallNode.callee.type === "FunctionExpression";
374 }
375
376 /**
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
382 */
383 function canBeAssignmentTarget(node) {
384 return node && (node.type === "Identifier" || node.type === "MemberExpression");
385 }
386
387 /**
388 * Report the node
389 * @param {ASTNode} node node to evaluate
390 * @returns {void}
391 * @private
392 */
393 function report(node) {
394 const leftParenToken = sourceCode.getTokenBefore(node);
395 const rightParenToken = sourceCode.getTokenAfter(node);
396
397 if (!isParenthesisedTwice(node)) {
398 if (tokensToIgnore.has(sourceCode.getFirstToken(node))) {
399 return;
400 }
401
402 if (isIIFE(node) && !isParenthesised(node.callee)) {
403 return;
404 }
405 }
406
407 /**
408 * Finishes reporting
409 * @returns {void}
410 * @private
411 */
412 function finishReport() {
413 context.report({
414 node,
415 loc: leftParenToken.loc,
416 messageId: "unexpected",
417 fix(fixer) {
418 const parenthesizedSource = sourceCode.text.slice(leftParenToken.range[1], rightParenToken.range[0]);
419
420 return fixer.replaceTextRange([
421 leftParenToken.range[0],
422 rightParenToken.range[1]
423 ], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource + (requiresTrailingSpace(node) ? " " : ""));
424 }
425 });
426 }
427
428 if (reportsBuffer) {
429 reportsBuffer.reports.push({ node, finishReport });
430 return;
431 }
432
433 finishReport();
434 }
435
436 /**
437 * Evaluate a argument of the node.
438 * @param {ASTNode} node node to evaluate
439 * @returns {void}
440 * @private
441 */
442 function checkArgumentWithPrecedence(node) {
443 if (hasExcessParensWithPrecedence(node.argument, precedence(node))) {
444 report(node.argument);
445 }
446 }
447
448 /**
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
452 */
453 function doesMemberExpressionContainCallExpression(node) {
454 let currentNode = node.object;
455 let currentNodeType = node.object.type;
456
457 while (currentNodeType === "MemberExpression") {
458 currentNode = currentNode.object;
459 currentNodeType = currentNode.type;
460 }
461
462 return currentNodeType === "CallExpression";
463 }
464
465 /**
466 * Evaluate a new call
467 * @param {ASTNode} node node to evaluate
468 * @returns {void}
469 * @private
470 */
471 function checkCallNew(node) {
472 const callee = node.callee;
473
474 if (hasExcessParensWithPrecedence(callee, precedence(node))) {
475 if (
476 hasDoubleExcessParens(callee) ||
477 !(
478 isIIFE(node) ||
479
480 // (new A)(); new (new A)();
481 (
482 callee.type === "NewExpression" &&
483 !isNewExpressionWithParens(callee) &&
484 !(
485 node.type === "NewExpression" &&
486 !isNewExpressionWithParens(node)
487 )
488 ) ||
489
490 // new (a().b)(); new (a.b().c);
491 (
492 node.type === "NewExpression" &&
493 callee.type === "MemberExpression" &&
494 doesMemberExpressionContainCallExpression(callee)
495 ) ||
496
497 // (a?.b)(); (a?.())();
498 (
499 !node.optional &&
500 callee.type === "ChainExpression"
501 )
502 )
503 ) {
504 report(node.callee);
505 }
506 }
507 node.arguments
508 .filter(arg => hasExcessParensWithPrecedence(arg, PRECEDENCE_OF_ASSIGNMENT_EXPR))
509 .forEach(report);
510 }
511
512 /**
513 * Evaluate binary logicals
514 * @param {ASTNode} node node to evaluate
515 * @returns {void}
516 * @private
517 */
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");
525
526 if (!shouldSkipLeft && hasExcessParens(node.left)) {
527 if (
528 !(["AwaitExpression", "UnaryExpression"].includes(node.left.type) && isExponentiation) &&
529 !astUtils.isMixedLogicalAndCoalesceExpressions(node.left, node) &&
530 (leftPrecedence > prec || (leftPrecedence === prec && !isExponentiation)) ||
531 isParenthesisedTwice(node.left)
532 ) {
533 report(node.left);
534 }
535 }
536
537 if (!shouldSkipRight && hasExcessParens(node.right)) {
538 if (
539 !astUtils.isMixedLogicalAndCoalesceExpressions(node.right, node) &&
540 (rightPrecedence > prec || (rightPrecedence === prec && isExponentiation)) ||
541 isParenthesisedTwice(node.right)
542 ) {
543 report(node.right);
544 }
545 }
546 }
547
548 /**
549 * Check the parentheses around the super class of the given class definition.
550 * @param {ASTNode} node The node of class declarations to check.
551 * @returns {void}
552 */
553 function checkClass(node) {
554 if (!node.superClass) {
555 return;
556 }
557
558 /*
559 * If `node.superClass` is a LeftHandSideExpression, parentheses are extra.
560 * Otherwise, parentheses are needed.
561 */
562 const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR
563 ? hasExcessParens(node.superClass)
564 : hasDoubleExcessParens(node.superClass);
565
566 if (hasExtraParens) {
567 report(node.superClass);
568 }
569 }
570
571 /**
572 * Check the parentheses around the argument of the given spread operator.
573 * @param {ASTNode} node The node of spread elements/properties to check.
574 * @returns {void}
575 */
576 function checkSpreadOperator(node) {
577 if (hasExcessParensWithPrecedence(node.argument, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
578 report(node.argument);
579 }
580 }
581
582 /**
583 * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration
584 * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node
585 * @returns {void}
586 */
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;
592
593 if (
594 astUtils.isOpeningParenToken(firstToken) &&
595 (
596 astUtils.isOpeningBraceToken(secondToken) ||
597 secondToken.type === "Keyword" && (
598 secondToken.value === "function" ||
599 secondToken.value === "class" ||
600 secondToken.value === "let" &&
601 tokenAfterClosingParens &&
602 (
603 astUtils.isOpeningBracketToken(tokenAfterClosingParens) ||
604 tokenAfterClosingParens.type === "Identifier"
605 )
606 ) ||
607 secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function"
608 )
609 ) {
610 tokensToIgnore.add(secondToken);
611 }
612
613 const hasExtraParens = node.parent.type === "ExportDefaultDeclaration"
614 ? hasExcessParensWithPrecedence(node, PRECEDENCE_OF_ASSIGNMENT_EXPR)
615 : hasExcessParens(node);
616
617 if (hasExtraParens) {
618 report(node);
619 }
620 }
621
622 /**
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.
628 */
629 function pathToAncestor(node, ancestor) {
630 const path = [node];
631 let currentNode = node;
632
633 while (currentNode !== ancestor) {
634
635 currentNode = currentNode.parent;
636
637 /* istanbul ignore if */
638 if (currentNode === null) {
639 throw new Error("Nodes are not in the ancestor-descendant relationship.");
640 }
641
642 path.push(currentNode);
643 }
644
645 return path;
646 }
647
648 /**
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.
654 */
655 function pathToDescendant(node, descendant) {
656 return pathToAncestor(descendant, node).reverse();
657 }
658
659 /**
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.
665 */
666 function isSafelyEnclosingInExpression(node, child) {
667 switch (node.type) {
668 case "ArrayExpression":
669 case "ArrayPattern":
670 case "BlockStatement":
671 case "ObjectExpression":
672 case "ObjectPattern":
673 case "TemplateLiteral":
674 return true;
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;
685 default:
686 return false;
687 }
688 }
689
690 /**
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.
693 * @returns {void}
694 */
695 function startNewReportsBuffering() {
696 reportsBuffer = {
697 upper: reportsBuffer,
698 inExpressionNodes: [],
699 reports: []
700 };
701 }
702
703 /**
704 * Ends the current reports buffering.
705 * @returns {void}
706 */
707 function endCurrentReportsBuffering() {
708 const { upper, inExpressionNodes, reports } = reportsBuffer;
709
710 if (upper) {
711 upper.inExpressionNodes.push(...inExpressionNodes);
712 upper.reports.push(...reports);
713 } else {
714
715 // flush remaining reports
716 reports.forEach(({ finishReport }) => finishReport());
717 }
718
719 reportsBuffer = upper;
720 }
721
722 /**
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.
726 */
727 function isInCurrentReportsBuffer(node) {
728 return reportsBuffer.reports.some(r => r.node === node);
729 }
730
731 /**
732 * Removes the given node from the current reports buffer.
733 * @param {ASTNode} node Node to remove.
734 * @returns {void}
735 */
736 function removeFromCurrentReportsBuffer(node) {
737 reportsBuffer.reports = reportsBuffer.reports.filter(r => r.node !== node);
738 }
739
740 /**
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.
744 */
745 function isMemberExpInNewCallee(node) {
746 if (node.type === "MemberExpression") {
747 return node.parent.type === "NewExpression" && node.parent.callee === node
748 ? true
749 : node.parent.object === node && isMemberExpInNewCallee(node.parent);
750 }
751 return false;
752 }
753
754 return {
755 ArrayExpression(node) {
756 node.elements
757 .filter(e => e && hasExcessParensWithPrecedence(e, PRECEDENCE_OF_ASSIGNMENT_EXPR))
758 .forEach(report);
759 },
760
761 ArrayPattern(node) {
762 node.elements
763 .filter(e => canBeAssignmentTarget(e) && hasExcessParens(e))
764 .forEach(report);
765 },
766
767 ArrowFunctionExpression(node) {
768 if (isReturnAssignException(node)) {
769 return;
770 }
771
772 if (node.body.type === "ConditionalExpression" &&
773 IGNORE_ARROW_CONDITIONALS
774 ) {
775 return;
776 }
777
778 if (node.body.type !== "BlockStatement") {
779 const firstBodyToken = sourceCode.getFirstToken(node.body, astUtils.isNotOpeningParenToken);
780 const tokenBeforeFirst = sourceCode.getTokenBefore(firstBodyToken);
781
782 if (astUtils.isOpeningParenToken(tokenBeforeFirst) && astUtils.isOpeningBraceToken(firstBodyToken)) {
783 tokensToIgnore.add(firstBodyToken);
784 }
785 if (hasExcessParensWithPrecedence(node.body, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
786 report(node.body);
787 }
788 }
789 },
790
791 AssignmentExpression(node) {
792 if (canBeAssignmentTarget(node.left) && hasExcessParens(node.left)) {
793 report(node.left);
794 }
795
796 if (!isReturnAssignException(node) && hasExcessParensWithPrecedence(node.right, precedence(node))) {
797 report(node.right);
798 }
799 },
800
801 BinaryExpression(node) {
802 if (reportsBuffer && node.operator === "in") {
803 reportsBuffer.inExpressionNodes.push(node);
804 }
805
806 checkBinaryLogical(node);
807 },
808
809 CallExpression: checkCallNew,
810
811 ClassBody(node) {
812 node.body
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));
816 },
817
818 ConditionalExpression(node) {
819 if (isReturnAssignException(node)) {
820 return;
821 }
822 if (
823 !isCondAssignException(node) &&
824 hasExcessParensWithPrecedence(node.test, precedence({ type: "LogicalExpression", operator: "||" }))
825 ) {
826 report(node.test);
827 }
828
829 if (hasExcessParensWithPrecedence(node.consequent, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
830 report(node.consequent);
831 }
832
833 if (hasExcessParensWithPrecedence(node.alternate, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
834 report(node.alternate);
835 }
836 },
837
838 DoWhileStatement(node) {
839 if (hasExcessParens(node.test) && !isCondAssignException(node)) {
840 report(node.test);
841 }
842 },
843
844 ExportDefaultDeclaration: node => checkExpressionOrExportStatement(node.declaration),
845 ExpressionStatement: node => checkExpressionOrExportStatement(node.expression),
846
847 ForInStatement(node) {
848 if (node.left.type !== "VariableDeclaration") {
849 const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken);
850
851 if (
852 firstLeftToken.value === "let" &&
853 astUtils.isOpeningBracketToken(
854 sourceCode.getTokenAfter(firstLeftToken, astUtils.isNotClosingParenToken)
855 )
856 ) {
857
858 // ForInStatement#left expression cannot start with `let[`.
859 tokensToIgnore.add(firstLeftToken);
860 }
861 }
862
863 if (hasExcessParens(node.left)) {
864 report(node.left);
865 }
866
867 if (hasExcessParens(node.right)) {
868 report(node.right);
869 }
870 },
871
872 ForOfStatement(node) {
873 if (node.left.type !== "VariableDeclaration") {
874 const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken);
875
876 if (firstLeftToken.value === "let") {
877
878 // ForOfStatement#left expression cannot start with `let`.
879 tokensToIgnore.add(firstLeftToken);
880 }
881 }
882
883 if (hasExcessParens(node.left)) {
884 report(node.left);
885 }
886
887 if (hasExcessParensWithPrecedence(node.right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
888 report(node.right);
889 }
890 },
891
892 ForStatement(node) {
893 if (node.test && hasExcessParens(node.test) && !isCondAssignException(node)) {
894 report(node.test);
895 }
896
897 if (node.update && hasExcessParens(node.update)) {
898 report(node.update);
899 }
900
901 if (node.init) {
902
903 if (node.init.type !== "VariableDeclaration") {
904 const firstToken = sourceCode.getFirstToken(node.init, astUtils.isNotOpeningParenToken);
905
906 if (
907 firstToken.value === "let" &&
908 astUtils.isOpeningBracketToken(
909 sourceCode.getTokenAfter(firstToken, astUtils.isNotClosingParenToken)
910 )
911 ) {
912
913 // ForStatement#init expression cannot start with `let[`.
914 tokensToIgnore.add(firstToken);
915 }
916 }
917
918 startNewReportsBuffering();
919
920 if (hasExcessParens(node.init)) {
921 report(node.init);
922 }
923 }
924 },
925
926 "ForStatement > *.init:exit"(node) {
927
928 /*
929 * Removing parentheses around `in` expressions might change semantics and cause errors.
930 *
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; ;);
935 */
936
937 if (reportsBuffer.reports.length) {
938 reportsBuffer.inExpressionNodes.forEach(inExpressionNode => {
939 const path = pathToDescendant(node, inExpressionNode);
940 let nodeToExclude;
941
942 for (let i = 0; i < path.length; i++) {
943 const pathNode = path[i];
944
945 if (i < path.length - 1) {
946 const nextPathNode = path[i + 1];
947
948 if (isSafelyEnclosingInExpression(pathNode, nextPathNode)) {
949
950 // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]').
951 return;
952 }
953 }
954
955 if (isParenthesised(pathNode)) {
956 if (isInCurrentReportsBuffer(pathNode)) {
957
958 // This node was supposed to be reported, but parentheses might be necessary.
959
960 if (isParenthesisedTwice(pathNode)) {
961
962 /*
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.
966 */
967 return;
968 }
969
970 // Exclude the outermost node only.
971 if (!nodeToExclude) {
972 nodeToExclude = pathNode;
973 }
974
975 // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside.
976
977 } else {
978
979 // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'.
980 return;
981 }
982 }
983 }
984
985 // Exclude the node from the list (i.e. treat parentheses as necessary)
986 removeFromCurrentReportsBuffer(nodeToExclude);
987 });
988 }
989
990 endCurrentReportsBuffering();
991 },
992
993 IfStatement(node) {
994 if (hasExcessParens(node.test) && !isCondAssignException(node)) {
995 report(node.test);
996 }
997 },
998
999 ImportExpression(node) {
1000 const { source } = node;
1001
1002 if (source.type === "SequenceExpression") {
1003 if (hasDoubleExcessParens(source)) {
1004 report(source);
1005 }
1006 } else if (hasExcessParens(source)) {
1007 report(source);
1008 }
1009 },
1010
1011 LogicalExpression: checkBinaryLogical,
1012
1013 MemberExpression(node) {
1014 const shouldAllowWrapOnce = isMemberExpInNewCallee(node) &&
1015 doesMemberExpressionContainCallExpression(node);
1016 const nodeObjHasExcessParens = shouldAllowWrapOnce
1017 ? hasDoubleExcessParens(node.object)
1018 : hasExcessParens(node.object) &&
1019 !(
1020 isImmediateFunctionPrototypeMethodCall(node.parent) &&
1021 node.parent.callee === node &&
1022 IGNORE_FUNCTION_PROTOTYPE_METHODS
1023 );
1024
1025 if (
1026 nodeObjHasExcessParens &&
1027 precedence(node.object) >= precedence(node) &&
1028 (
1029 node.computed ||
1030 !(
1031 astUtils.isDecimalInteger(node.object) ||
1032
1033 // RegExp literal is allowed to have parens (#1589)
1034 (node.object.type === "Literal" && node.object.regex)
1035 )
1036 )
1037 ) {
1038 report(node.object);
1039 }
1040
1041 if (nodeObjHasExcessParens &&
1042 node.object.type === "CallExpression"
1043 ) {
1044 report(node.object);
1045 }
1046
1047 if (nodeObjHasExcessParens &&
1048 !IGNORE_NEW_IN_MEMBER_EXPR &&
1049 node.object.type === "NewExpression" &&
1050 isNewExpressionWithParens(node.object)) {
1051 report(node.object);
1052 }
1053
1054 if (nodeObjHasExcessParens &&
1055 node.optional &&
1056 node.object.type === "ChainExpression"
1057 ) {
1058 report(node.object);
1059 }
1060
1061 if (node.computed && hasExcessParens(node.property)) {
1062 report(node.property);
1063 }
1064 },
1065
1066 NewExpression: checkCallNew,
1067
1068 ObjectExpression(node) {
1069 node.properties
1070 .filter(property => property.value && hasExcessParensWithPrecedence(property.value, PRECEDENCE_OF_ASSIGNMENT_EXPR))
1071 .forEach(property => report(property.value));
1072 },
1073
1074 ObjectPattern(node) {
1075 node.properties
1076 .filter(property => {
1077 const value = property.value;
1078
1079 return canBeAssignmentTarget(value) && hasExcessParens(value);
1080 }).forEach(property => report(property.value));
1081 },
1082
1083 Property(node) {
1084 if (node.computed) {
1085 const { key } = node;
1086
1087 if (key && hasExcessParensWithPrecedence(key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
1088 report(key);
1089 }
1090 }
1091 },
1092
1093 RestElement(node) {
1094 const argument = node.argument;
1095
1096 if (canBeAssignmentTarget(argument) && hasExcessParens(argument)) {
1097 report(argument);
1098 }
1099 },
1100
1101 ReturnStatement(node) {
1102 const returnToken = sourceCode.getFirstToken(node);
1103
1104 if (isReturnAssignException(node)) {
1105 return;
1106 }
1107
1108 if (node.argument &&
1109 hasExcessParensNoLineTerminator(returnToken, node.argument) &&
1110
1111 // RegExp literal is allowed to have parens (#1589)
1112 !(node.argument.type === "Literal" && node.argument.regex)) {
1113 report(node.argument);
1114 }
1115 },
1116
1117 SequenceExpression(node) {
1118 const precedenceOfNode = precedence(node);
1119
1120 node.expressions
1121 .filter(e => hasExcessParensWithPrecedence(e, precedenceOfNode))
1122 .forEach(report);
1123 },
1124
1125 SwitchCase(node) {
1126 if (node.test && hasExcessParens(node.test)) {
1127 report(node.test);
1128 }
1129 },
1130
1131 SwitchStatement(node) {
1132 if (hasExcessParens(node.discriminant)) {
1133 report(node.discriminant);
1134 }
1135 },
1136
1137 ThrowStatement(node) {
1138 const throwToken = sourceCode.getFirstToken(node);
1139
1140 if (hasExcessParensNoLineTerminator(throwToken, node.argument)) {
1141 report(node.argument);
1142 }
1143 },
1144
1145 UnaryExpression: checkArgumentWithPrecedence,
1146 UpdateExpression(node) {
1147 if (node.prefix) {
1148 checkArgumentWithPrecedence(node);
1149 } else {
1150 const { argument } = node;
1151 const operatorToken = sourceCode.getLastToken(node);
1152
1153 if (argument.loc.end.line === operatorToken.loc.start.line) {
1154 checkArgumentWithPrecedence(node);
1155 } else {
1156 if (hasDoubleExcessParens(argument)) {
1157 report(argument);
1158 }
1159 }
1160 }
1161 },
1162 AwaitExpression: checkArgumentWithPrecedence,
1163
1164 VariableDeclarator(node) {
1165 if (
1166 node.init && hasExcessParensWithPrecedence(node.init, PRECEDENCE_OF_ASSIGNMENT_EXPR) &&
1167
1168 // RegExp literal is allowed to have parens (#1589)
1169 !(node.init.type === "Literal" && node.init.regex)
1170 ) {
1171 report(node.init);
1172 }
1173 },
1174
1175 WhileStatement(node) {
1176 if (hasExcessParens(node.test) && !isCondAssignException(node)) {
1177 report(node.test);
1178 }
1179 },
1180
1181 WithStatement(node) {
1182 if (hasExcessParens(node.object)) {
1183 report(node.object);
1184 }
1185 },
1186
1187 YieldExpression(node) {
1188 if (node.argument) {
1189 const yieldToken = sourceCode.getFirstToken(node);
1190
1191 if ((precedence(node.argument) >= precedence(node) &&
1192 hasExcessParensNoLineTerminator(yieldToken, node.argument)) ||
1193 hasDoubleExcessParens(node.argument)) {
1194 report(node.argument);
1195 }
1196 }
1197 },
1198
1199 ClassDeclaration: checkClass,
1200 ClassExpression: checkClass,
1201
1202 SpreadElement: checkSpreadOperator,
1203 SpreadProperty: checkSpreadOperator,
1204 ExperimentalSpreadProperty: checkSpreadOperator,
1205
1206 TemplateLiteral(node) {
1207 node.expressions
1208 .filter(e => e && hasExcessParens(e))
1209 .forEach(report);
1210 },
1211
1212 AssignmentPattern(node) {
1213 const { left, right } = node;
1214
1215 if (canBeAssignmentTarget(left) && hasExcessParens(left)) {
1216 report(left);
1217 }
1218
1219 if (right && hasExcessParensWithPrecedence(right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
1220 report(right);
1221 }
1222 }
1223 };
1224
1225 }
1226};