You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1177 lines
46 KiB

4 years ago
  1. /**
  2. * @fileoverview Disallow parenthesising higher precedence subexpressions.
  3. * @author Michael Ficarra
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Rule Definition
  8. //------------------------------------------------------------------------------
  9. const { isParenthesized: isParenthesizedRaw } = require("eslint-utils");
  10. const astUtils = require("./utils/ast-utils.js");
  11. module.exports = {
  12. meta: {
  13. type: "layout",
  14. docs: {
  15. description: "disallow unnecessary parentheses",
  16. category: "Possible Errors",
  17. recommended: false,
  18. url: "https://eslint.org/docs/rules/no-extra-parens"
  19. },
  20. fixable: "code",
  21. schema: {
  22. anyOf: [
  23. {
  24. type: "array",
  25. items: [
  26. {
  27. enum: ["functions"]
  28. }
  29. ],
  30. minItems: 0,
  31. maxItems: 1
  32. },
  33. {
  34. type: "array",
  35. items: [
  36. {
  37. enum: ["all"]
  38. },
  39. {
  40. type: "object",
  41. properties: {
  42. conditionalAssign: { type: "boolean" },
  43. nestedBinaryExpressions: { type: "boolean" },
  44. returnAssign: { type: "boolean" },
  45. ignoreJSX: { enum: ["none", "all", "single-line", "multi-line"] },
  46. enforceForArrowConditionals: { type: "boolean" },
  47. enforceForSequenceExpressions: { type: "boolean" },
  48. enforceForNewInMemberExpressions: { type: "boolean" },
  49. enforceForFunctionPrototypeMethods: { type: "boolean" }
  50. },
  51. additionalProperties: false
  52. }
  53. ],
  54. minItems: 0,
  55. maxItems: 2
  56. }
  57. ]
  58. },
  59. messages: {
  60. unexpected: "Unnecessary parentheses around expression."
  61. }
  62. },
  63. create(context) {
  64. const sourceCode = context.getSourceCode();
  65. const tokensToIgnore = new WeakSet();
  66. const precedence = astUtils.getPrecedence;
  67. const ALL_NODES = context.options[0] !== "functions";
  68. const EXCEPT_COND_ASSIGN = ALL_NODES && context.options[1] && context.options[1].conditionalAssign === false;
  69. const NESTED_BINARY = ALL_NODES && context.options[1] && context.options[1].nestedBinaryExpressions === false;
  70. const EXCEPT_RETURN_ASSIGN = ALL_NODES && context.options[1] && context.options[1].returnAssign === false;
  71. const IGNORE_JSX = ALL_NODES && context.options[1] && context.options[1].ignoreJSX;
  72. const IGNORE_ARROW_CONDITIONALS = ALL_NODES && context.options[1] &&
  73. context.options[1].enforceForArrowConditionals === false;
  74. const IGNORE_SEQUENCE_EXPRESSIONS = ALL_NODES && context.options[1] &&
  75. context.options[1].enforceForSequenceExpressions === false;
  76. const IGNORE_NEW_IN_MEMBER_EXPR = ALL_NODES && context.options[1] &&
  77. context.options[1].enforceForNewInMemberExpressions === false;
  78. const IGNORE_FUNCTION_PROTOTYPE_METHODS = ALL_NODES && context.options[1] &&
  79. context.options[1].enforceForFunctionPrototypeMethods === false;
  80. const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({ type: "AssignmentExpression" });
  81. const PRECEDENCE_OF_UPDATE_EXPR = precedence({ type: "UpdateExpression" });
  82. let reportsBuffer;
  83. /**
  84. * Determines whether the given node is a `call` or `apply` method call, invoked directly on a `FunctionExpression` node.
  85. * Example: function(){}.call()
  86. * @param {ASTNode} node The node to be checked.
  87. * @returns {boolean} True if the node is an immediate `call` or `apply` method call.
  88. * @private
  89. */
  90. function isImmediateFunctionPrototypeMethodCall(node) {
  91. const callNode = astUtils.skipChainExpression(node);
  92. if (callNode.type !== "CallExpression") {
  93. return false;
  94. }
  95. const callee = astUtils.skipChainExpression(callNode.callee);
  96. return (
  97. callee.type === "MemberExpression" &&
  98. callee.object.type === "FunctionExpression" &&
  99. ["call", "apply"].includes(astUtils.getStaticPropertyName(callee))
  100. );
  101. }
  102. /**
  103. * Determines if this rule should be enforced for a node given the current configuration.
  104. * @param {ASTNode} node The node to be checked.
  105. * @returns {boolean} True if the rule should be enforced for this node.
  106. * @private
  107. */
  108. function ruleApplies(node) {
  109. if (node.type === "JSXElement" || node.type === "JSXFragment") {
  110. const isSingleLine = node.loc.start.line === node.loc.end.line;
  111. switch (IGNORE_JSX) {
  112. // Exclude this JSX element from linting
  113. case "all":
  114. return false;
  115. // Exclude this JSX element if it is multi-line element
  116. case "multi-line":
  117. return isSingleLine;
  118. // Exclude this JSX element if it is single-line element
  119. case "single-line":
  120. return !isSingleLine;
  121. // Nothing special to be done for JSX elements
  122. case "none":
  123. break;
  124. // no default
  125. }
  126. }
  127. if (node.type === "SequenceExpression" && IGNORE_SEQUENCE_EXPRESSIONS) {
  128. return false;
  129. }
  130. if (isImmediateFunctionPrototypeMethodCall(node) && IGNORE_FUNCTION_PROTOTYPE_METHODS) {
  131. return false;
  132. }
  133. return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
  134. }
  135. /**
  136. * Determines if a node is surrounded by parentheses.
  137. * @param {ASTNode} node The node to be checked.
  138. * @returns {boolean} True if the node is parenthesised.
  139. * @private
  140. */
  141. function isParenthesised(node) {
  142. return isParenthesizedRaw(1, node, sourceCode);
  143. }
  144. /**
  145. * Determines if a node is surrounded by parentheses twice.
  146. * @param {ASTNode} node The node to be checked.
  147. * @returns {boolean} True if the node is doubly parenthesised.
  148. * @private
  149. */
  150. function isParenthesisedTwice(node) {
  151. return isParenthesizedRaw(2, node, sourceCode);
  152. }
  153. /**
  154. * Determines if a node is surrounded by (potentially) invalid parentheses.
  155. * @param {ASTNode} node The node to be checked.
  156. * @returns {boolean} True if the node is incorrectly parenthesised.
  157. * @private
  158. */
  159. function hasExcessParens(node) {
  160. return ruleApplies(node) && isParenthesised(node);
  161. }
  162. /**
  163. * Determines if a node that is expected to be parenthesised is surrounded by
  164. * (potentially) invalid extra parentheses.
  165. * @param {ASTNode} node The node to be checked.
  166. * @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
  167. * @private
  168. */
  169. function hasDoubleExcessParens(node) {
  170. return ruleApplies(node) && isParenthesisedTwice(node);
  171. }
  172. /**
  173. * Determines if a node that is expected to be parenthesised is surrounded by
  174. * (potentially) invalid extra parentheses with considering precedence level of the node.
  175. * If the preference level of the node is not higher or equal to precedence lower limit, it also checks
  176. * whether the node is surrounded by parentheses twice or not.
  177. * @param {ASTNode} node The node to be checked.
  178. * @param {number} precedenceLowerLimit The lower limit of precedence.
  179. * @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
  180. * @private
  181. */
  182. function hasExcessParensWithPrecedence(node, precedenceLowerLimit) {
  183. if (ruleApplies(node) && isParenthesised(node)) {
  184. if (
  185. precedence(node) >= precedenceLowerLimit ||
  186. isParenthesisedTwice(node)
  187. ) {
  188. return true;
  189. }
  190. }
  191. return false;
  192. }
  193. /**
  194. * Determines if a node test expression is allowed to have a parenthesised assignment
  195. * @param {ASTNode} node The node to be checked.
  196. * @returns {boolean} True if the assignment can be parenthesised.
  197. * @private
  198. */
  199. function isCondAssignException(node) {
  200. return EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression";
  201. }
  202. /**
  203. * Determines if a node is in a return statement
  204. * @param {ASTNode} node The node to be checked.
  205. * @returns {boolean} True if the node is in a return statement.
  206. * @private
  207. */
  208. function isInReturnStatement(node) {
  209. for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
  210. if (
  211. currentNode.type === "ReturnStatement" ||
  212. (currentNode.type === "ArrowFunctionExpression" && currentNode.body.type !== "BlockStatement")
  213. ) {
  214. return true;
  215. }
  216. }
  217. return false;
  218. }
  219. /**
  220. * Determines if a constructor function is newed-up with parens
  221. * @param {ASTNode} newExpression The NewExpression node to be checked.
  222. * @returns {boolean} True if the constructor is called with parens.
  223. * @private
  224. */
  225. function isNewExpressionWithParens(newExpression) {
  226. const lastToken = sourceCode.getLastToken(newExpression);
  227. const penultimateToken = sourceCode.getTokenBefore(lastToken);
  228. return newExpression.arguments.length > 0 ||
  229. (
  230. // The expression should end with its own parens, e.g., new new foo() is not a new expression with parens
  231. astUtils.isOpeningParenToken(penultimateToken) &&
  232. astUtils.isClosingParenToken(lastToken) &&
  233. newExpression.callee.range[1] < newExpression.range[1]
  234. );
  235. }
  236. /**
  237. * Determines if a node is or contains an assignment expression
  238. * @param {ASTNode} node The node to be checked.
  239. * @returns {boolean} True if the node is or contains an assignment expression.
  240. * @private
  241. */
  242. function containsAssignment(node) {
  243. if (node.type === "AssignmentExpression") {
  244. return true;
  245. }
  246. if (node.type === "ConditionalExpression" &&
  247. (node.consequent.type === "AssignmentExpression" || node.alternate.type === "AssignmentExpression")) {
  248. return true;
  249. }
  250. if ((node.left && node.left.type === "AssignmentExpression") ||
  251. (node.right && node.right.type === "AssignmentExpression")) {
  252. return true;
  253. }
  254. return false;
  255. }
  256. /**
  257. * Determines if a node is contained by or is itself a return statement and is allowed to have a parenthesised assignment
  258. * @param {ASTNode} node The node to be checked.
  259. * @returns {boolean} True if the assignment can be parenthesised.
  260. * @private
  261. */
  262. function isReturnAssignException(node) {
  263. if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) {
  264. return false;
  265. }
  266. if (node.type === "ReturnStatement") {
  267. return node.argument && containsAssignment(node.argument);
  268. }
  269. if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
  270. return containsAssignment(node.body);
  271. }
  272. return containsAssignment(node);
  273. }
  274. /**
  275. * Determines if a node following a [no LineTerminator here] restriction is
  276. * surrounded by (potentially) invalid extra parentheses.
  277. * @param {Token} token The token preceding the [no LineTerminator here] restriction.
  278. * @param {ASTNode} node The node to be checked.
  279. * @returns {boolean} True if the node is incorrectly parenthesised.
  280. * @private
  281. */
  282. function hasExcessParensNoLineTerminator(token, node) {
  283. if (token.loc.end.line === node.loc.start.line) {
  284. return hasExcessParens(node);
  285. }
  286. return hasDoubleExcessParens(node);
  287. }
  288. /**
  289. * Determines whether a node should be preceded by an additional space when removing parens
  290. * @param {ASTNode} node node to evaluate; must be surrounded by parentheses
  291. * @returns {boolean} `true` if a space should be inserted before the node
  292. * @private
  293. */
  294. function requiresLeadingSpace(node) {
  295. const leftParenToken = sourceCode.getTokenBefore(node);
  296. const tokenBeforeLeftParen = sourceCode.getTokenBefore(leftParenToken, { includeComments: true });
  297. const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParenToken, { includeComments: true });
  298. return tokenBeforeLeftParen &&
  299. tokenBeforeLeftParen.range[1] === leftParenToken.range[0] &&
  300. leftParenToken.range[1] === tokenAfterLeftParen.range[0] &&
  301. !astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, tokenAfterLeftParen);
  302. }
  303. /**
  304. * Determines whether a node should be followed by an additional space when removing parens
  305. * @param {ASTNode} node node to evaluate; must be surrounded by parentheses
  306. * @returns {boolean} `true` if a space should be inserted after the node
  307. * @private
  308. */
  309. function requiresTrailingSpace(node) {
  310. const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 });
  311. const rightParenToken = nextTwoTokens[0];
  312. const tokenAfterRightParen = nextTwoTokens[1];
  313. const tokenBeforeRightParen = sourceCode.getLastToken(node);
  314. return rightParenToken && tokenAfterRightParen &&
  315. !sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) &&
  316. !astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen);
  317. }
  318. /**
  319. * Determines if a given expression node is an IIFE
  320. * @param {ASTNode} node The node to check
  321. * @returns {boolean} `true` if the given node is an IIFE
  322. */
  323. function isIIFE(node) {
  324. const maybeCallNode = astUtils.skipChainExpression(node);
  325. return maybeCallNode.type === "CallExpression" && maybeCallNode.callee.type === "FunctionExpression";
  326. }
  327. /**
  328. * Determines if the given node can be the assignment target in destructuring or the LHS of an assignment.
  329. * This is to avoid an autofix that could change behavior because parsers mistakenly allow invalid syntax,
  330. * such as `(a = b) = c` and `[(a = b) = c] = []`. Ideally, this function shouldn't be necessary.
  331. * @param {ASTNode} [node] The node to check
  332. * @returns {boolean} `true` if the given node can be a valid assignment target
  333. */
  334. function canBeAssignmentTarget(node) {
  335. return node && (node.type === "Identifier" || node.type === "MemberExpression");
  336. }
  337. /**
  338. * Report the node
  339. * @param {ASTNode} node node to evaluate
  340. * @returns {void}
  341. * @private
  342. */
  343. function report(node) {
  344. const leftParenToken = sourceCode.getTokenBefore(node);
  345. const rightParenToken = sourceCode.getTokenAfter(node);
  346. if (!isParenthesisedTwice(node)) {
  347. if (tokensToIgnore.has(sourceCode.getFirstToken(node))) {
  348. return;
  349. }
  350. if (isIIFE(node) && !isParenthesised(node.callee)) {
  351. return;
  352. }
  353. }
  354. /**
  355. * Finishes reporting
  356. * @returns {void}
  357. * @private
  358. */
  359. function finishReport() {
  360. context.report({
  361. node,
  362. loc: leftParenToken.loc,
  363. messageId: "unexpected",
  364. fix(fixer) {
  365. const parenthesizedSource = sourceCode.text.slice(leftParenToken.range[1], rightParenToken.range[0]);
  366. return fixer.replaceTextRange([
  367. leftParenToken.range[0],
  368. rightParenToken.range[1]
  369. ], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource + (requiresTrailingSpace(node) ? " " : ""));
  370. }
  371. });
  372. }
  373. if (reportsBuffer) {
  374. reportsBuffer.reports.push({ node, finishReport });
  375. return;
  376. }
  377. finishReport();
  378. }
  379. /**
  380. * Evaluate a argument of the node.
  381. * @param {ASTNode} node node to evaluate
  382. * @returns {void}
  383. * @private
  384. */
  385. function checkArgumentWithPrecedence(node) {
  386. if (hasExcessParensWithPrecedence(node.argument, precedence(node))) {
  387. report(node.argument);
  388. }
  389. }
  390. /**
  391. * Check if a member expression contains a call expression
  392. * @param {ASTNode} node MemberExpression node to evaluate
  393. * @returns {boolean} true if found, false if not
  394. */
  395. function doesMemberExpressionContainCallExpression(node) {
  396. let currentNode = node.object;
  397. let currentNodeType = node.object.type;
  398. while (currentNodeType === "MemberExpression") {
  399. currentNode = currentNode.object;
  400. currentNodeType = currentNode.type;
  401. }
  402. return currentNodeType === "CallExpression";
  403. }
  404. /**
  405. * Evaluate a new call
  406. * @param {ASTNode} node node to evaluate
  407. * @returns {void}
  408. * @private
  409. */
  410. function checkCallNew(node) {
  411. const callee = node.callee;
  412. if (hasExcessParensWithPrecedence(callee, precedence(node))) {
  413. const hasNewParensException = callee.type === "NewExpression" && !isNewExpressionWithParens(callee);
  414. if (
  415. hasDoubleExcessParens(callee) ||
  416. !isIIFE(node) &&
  417. !hasNewParensException &&
  418. !(
  419. // Allow extra parens around a new expression if they are intervening parentheses.
  420. node.type === "NewExpression" &&
  421. callee.type === "MemberExpression" &&
  422. doesMemberExpressionContainCallExpression(callee)
  423. ) &&
  424. !(!node.optional && callee.type === "ChainExpression")
  425. ) {
  426. report(node.callee);
  427. }
  428. }
  429. node.arguments
  430. .filter(arg => hasExcessParensWithPrecedence(arg, PRECEDENCE_OF_ASSIGNMENT_EXPR))
  431. .forEach(report);
  432. }
  433. /**
  434. * Evaluate binary logicals
  435. * @param {ASTNode} node node to evaluate
  436. * @returns {void}
  437. * @private
  438. */
  439. function checkBinaryLogical(node) {
  440. const prec = precedence(node);
  441. const leftPrecedence = precedence(node.left);
  442. const rightPrecedence = precedence(node.right);
  443. const isExponentiation = node.operator === "**";
  444. const shouldSkipLeft = NESTED_BINARY && (node.left.type === "BinaryExpression" || node.left.type === "LogicalExpression");
  445. const shouldSkipRight = NESTED_BINARY && (node.right.type === "BinaryExpression" || node.right.type === "LogicalExpression");
  446. if (!shouldSkipLeft && hasExcessParens(node.left)) {
  447. if (
  448. !(node.left.type === "UnaryExpression" && isExponentiation) &&
  449. !astUtils.isMixedLogicalAndCoalesceExpressions(node.left, node) &&
  450. (leftPrecedence > prec || (leftPrecedence === prec && !isExponentiation)) ||
  451. isParenthesisedTwice(node.left)
  452. ) {
  453. report(node.left);
  454. }
  455. }
  456. if (!shouldSkipRight && hasExcessParens(node.right)) {
  457. if (
  458. !astUtils.isMixedLogicalAndCoalesceExpressions(node.right, node) &&
  459. (rightPrecedence > prec || (rightPrecedence === prec && isExponentiation)) ||
  460. isParenthesisedTwice(node.right)
  461. ) {
  462. report(node.right);
  463. }
  464. }
  465. }
  466. /**
  467. * Check the parentheses around the super class of the given class definition.
  468. * @param {ASTNode} node The node of class declarations to check.
  469. * @returns {void}
  470. */
  471. function checkClass(node) {
  472. if (!node.superClass) {
  473. return;
  474. }
  475. /*
  476. * If `node.superClass` is a LeftHandSideExpression, parentheses are extra.
  477. * Otherwise, parentheses are needed.
  478. */
  479. const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR
  480. ? hasExcessParens(node.superClass)
  481. : hasDoubleExcessParens(node.superClass);
  482. if (hasExtraParens) {
  483. report(node.superClass);
  484. }
  485. }
  486. /**
  487. * Check the parentheses around the argument of the given spread operator.
  488. * @param {ASTNode} node The node of spread elements/properties to check.
  489. * @returns {void}
  490. */
  491. function checkSpreadOperator(node) {
  492. if (hasExcessParensWithPrecedence(node.argument, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  493. report(node.argument);
  494. }
  495. }
  496. /**
  497. * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration
  498. * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node
  499. * @returns {void}
  500. */
  501. function checkExpressionOrExportStatement(node) {
  502. const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node);
  503. const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken);
  504. const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null;
  505. const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null;
  506. if (
  507. astUtils.isOpeningParenToken(firstToken) &&
  508. (
  509. astUtils.isOpeningBraceToken(secondToken) ||
  510. secondToken.type === "Keyword" && (
  511. secondToken.value === "function" ||
  512. secondToken.value === "class" ||
  513. secondToken.value === "let" &&
  514. tokenAfterClosingParens &&
  515. (
  516. astUtils.isOpeningBracketToken(tokenAfterClosingParens) ||
  517. tokenAfterClosingParens.type === "Identifier"
  518. )
  519. ) ||
  520. secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function"
  521. )
  522. ) {
  523. tokensToIgnore.add(secondToken);
  524. }
  525. const hasExtraParens = node.parent.type === "ExportDefaultDeclaration"
  526. ? hasExcessParensWithPrecedence(node, PRECEDENCE_OF_ASSIGNMENT_EXPR)
  527. : hasExcessParens(node);
  528. if (hasExtraParens) {
  529. report(node);
  530. }
  531. }
  532. /**
  533. * Finds the path from the given node to the specified ancestor.
  534. * @param {ASTNode} node First node in the path.
  535. * @param {ASTNode} ancestor Last node in the path.
  536. * @returns {ASTNode[]} Path, including both nodes.
  537. * @throws {Error} If the given node does not have the specified ancestor.
  538. */
  539. function pathToAncestor(node, ancestor) {
  540. const path = [node];
  541. let currentNode = node;
  542. while (currentNode !== ancestor) {
  543. currentNode = currentNode.parent;
  544. /* istanbul ignore if */
  545. if (currentNode === null) {
  546. throw new Error("Nodes are not in the ancestor-descendant relationship.");
  547. }
  548. path.push(currentNode);
  549. }
  550. return path;
  551. }
  552. /**
  553. * Finds the path from the given node to the specified descendant.
  554. * @param {ASTNode} node First node in the path.
  555. * @param {ASTNode} descendant Last node in the path.
  556. * @returns {ASTNode[]} Path, including both nodes.
  557. * @throws {Error} If the given node does not have the specified descendant.
  558. */
  559. function pathToDescendant(node, descendant) {
  560. return pathToAncestor(descendant, node).reverse();
  561. }
  562. /**
  563. * Checks whether the syntax of the given ancestor of an 'in' expression inside a for-loop initializer
  564. * is preventing the 'in' keyword from being interpreted as a part of an ill-formed for-in loop.
  565. * @param {ASTNode} node Ancestor of an 'in' expression.
  566. * @param {ASTNode} child Child of the node, ancestor of the same 'in' expression or the 'in' expression itself.
  567. * @returns {boolean} True if the keyword 'in' would be interpreted as the 'in' operator, without any parenthesis.
  568. */
  569. function isSafelyEnclosingInExpression(node, child) {
  570. switch (node.type) {
  571. case "ArrayExpression":
  572. case "ArrayPattern":
  573. case "BlockStatement":
  574. case "ObjectExpression":
  575. case "ObjectPattern":
  576. case "TemplateLiteral":
  577. return true;
  578. case "ArrowFunctionExpression":
  579. case "FunctionExpression":
  580. return node.params.includes(child);
  581. case "CallExpression":
  582. case "NewExpression":
  583. return node.arguments.includes(child);
  584. case "MemberExpression":
  585. return node.computed && node.property === child;
  586. case "ConditionalExpression":
  587. return node.consequent === child;
  588. default:
  589. return false;
  590. }
  591. }
  592. /**
  593. * Starts a new reports buffering. Warnings will be stored in a buffer instead of being reported immediately.
  594. * An additional logic that requires multiple nodes (e.g. a whole subtree) may dismiss some of the stored warnings.
  595. * @returns {void}
  596. */
  597. function startNewReportsBuffering() {
  598. reportsBuffer = {
  599. upper: reportsBuffer,
  600. inExpressionNodes: [],
  601. reports: []
  602. };
  603. }
  604. /**
  605. * Ends the current reports buffering.
  606. * @returns {void}
  607. */
  608. function endCurrentReportsBuffering() {
  609. const { upper, inExpressionNodes, reports } = reportsBuffer;
  610. if (upper) {
  611. upper.inExpressionNodes.push(...inExpressionNodes);
  612. upper.reports.push(...reports);
  613. } else {
  614. // flush remaining reports
  615. reports.forEach(({ finishReport }) => finishReport());
  616. }
  617. reportsBuffer = upper;
  618. }
  619. /**
  620. * Checks whether the given node is in the current reports buffer.
  621. * @param {ASTNode} node Node to check.
  622. * @returns {boolean} True if the node is in the current buffer, false otherwise.
  623. */
  624. function isInCurrentReportsBuffer(node) {
  625. return reportsBuffer.reports.some(r => r.node === node);
  626. }
  627. /**
  628. * Removes the given node from the current reports buffer.
  629. * @param {ASTNode} node Node to remove.
  630. * @returns {void}
  631. */
  632. function removeFromCurrentReportsBuffer(node) {
  633. reportsBuffer.reports = reportsBuffer.reports.filter(r => r.node !== node);
  634. }
  635. /**
  636. * Checks whether a node is a MemberExpression at NewExpression's callee.
  637. * @param {ASTNode} node node to check.
  638. * @returns {boolean} True if the node is a MemberExpression at NewExpression's callee. false otherwise.
  639. */
  640. function isMemberExpInNewCallee(node) {
  641. if (node.type === "MemberExpression") {
  642. return node.parent.type === "NewExpression" && node.parent.callee === node
  643. ? true
  644. : node.parent.object === node && isMemberExpInNewCallee(node.parent);
  645. }
  646. return false;
  647. }
  648. return {
  649. ArrayExpression(node) {
  650. node.elements
  651. .filter(e => e && hasExcessParensWithPrecedence(e, PRECEDENCE_OF_ASSIGNMENT_EXPR))
  652. .forEach(report);
  653. },
  654. ArrayPattern(node) {
  655. node.elements
  656. .filter(e => canBeAssignmentTarget(e) && hasExcessParens(e))
  657. .forEach(report);
  658. },
  659. ArrowFunctionExpression(node) {
  660. if (isReturnAssignException(node)) {
  661. return;
  662. }
  663. if (node.body.type === "ConditionalExpression" &&
  664. IGNORE_ARROW_CONDITIONALS
  665. ) {
  666. return;
  667. }
  668. if (node.body.type !== "BlockStatement") {
  669. const firstBodyToken = sourceCode.getFirstToken(node.body, astUtils.isNotOpeningParenToken);
  670. const tokenBeforeFirst = sourceCode.getTokenBefore(firstBodyToken);
  671. if (astUtils.isOpeningParenToken(tokenBeforeFirst) && astUtils.isOpeningBraceToken(firstBodyToken)) {
  672. tokensToIgnore.add(firstBodyToken);
  673. }
  674. if (hasExcessParensWithPrecedence(node.body, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  675. report(node.body);
  676. }
  677. }
  678. },
  679. AssignmentExpression(node) {
  680. if (canBeAssignmentTarget(node.left) && hasExcessParens(node.left)) {
  681. report(node.left);
  682. }
  683. if (!isReturnAssignException(node) && hasExcessParensWithPrecedence(node.right, precedence(node))) {
  684. report(node.right);
  685. }
  686. },
  687. BinaryExpression(node) {
  688. if (reportsBuffer && node.operator === "in") {
  689. reportsBuffer.inExpressionNodes.push(node);
  690. }
  691. checkBinaryLogical(node);
  692. },
  693. CallExpression: checkCallNew,
  694. ClassBody(node) {
  695. node.body
  696. .filter(member => member.type === "MethodDefinition" && member.computed && member.key)
  697. .filter(member => hasExcessParensWithPrecedence(member.key, PRECEDENCE_OF_ASSIGNMENT_EXPR))
  698. .forEach(member => report(member.key));
  699. },
  700. ConditionalExpression(node) {
  701. if (isReturnAssignException(node)) {
  702. return;
  703. }
  704. if (
  705. !isCondAssignException(node) &&
  706. hasExcessParensWithPrecedence(node.test, precedence({ type: "LogicalExpression", operator: "||" }))
  707. ) {
  708. report(node.test);
  709. }
  710. if (hasExcessParensWithPrecedence(node.consequent, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  711. report(node.consequent);
  712. }
  713. if (hasExcessParensWithPrecedence(node.alternate, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  714. report(node.alternate);
  715. }
  716. },
  717. DoWhileStatement(node) {
  718. if (hasExcessParens(node.test) && !isCondAssignException(node)) {
  719. report(node.test);
  720. }
  721. },
  722. ExportDefaultDeclaration: node => checkExpressionOrExportStatement(node.declaration),
  723. ExpressionStatement: node => checkExpressionOrExportStatement(node.expression),
  724. "ForInStatement, ForOfStatement"(node) {
  725. if (node.left.type !== "VariableDeclarator") {
  726. const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken);
  727. if (
  728. firstLeftToken.value === "let" && (
  729. /*
  730. * If `let` is the only thing on the left side of the loop, it's the loop variable: `for ((let) of foo);`
  731. * Removing it will cause a syntax error, because it will be parsed as the start of a VariableDeclarator.
  732. */
  733. (firstLeftToken.range[1] === node.left.range[1] || /*
  734. * If `let` is followed by a `[` token, it's a property access on the `let` value: `for ((let[foo]) of bar);`
  735. * Removing it will cause the property access to be parsed as a destructuring declaration of `foo` instead.
  736. */
  737. astUtils.isOpeningBracketToken(
  738. sourceCode.getTokenAfter(firstLeftToken, astUtils.isNotClosingParenToken)
  739. ))
  740. )
  741. ) {
  742. tokensToIgnore.add(firstLeftToken);
  743. }
  744. }
  745. if (node.type === "ForOfStatement") {
  746. const hasExtraParens = node.right.type === "SequenceExpression"
  747. ? hasDoubleExcessParens(node.right)
  748. : hasExcessParens(node.right);
  749. if (hasExtraParens) {
  750. report(node.right);
  751. }
  752. } else if (hasExcessParens(node.right)) {
  753. report(node.right);
  754. }
  755. if (hasExcessParens(node.left)) {
  756. report(node.left);
  757. }
  758. },
  759. ForStatement(node) {
  760. if (node.test && hasExcessParens(node.test) && !isCondAssignException(node)) {
  761. report(node.test);
  762. }
  763. if (node.update && hasExcessParens(node.update)) {
  764. report(node.update);
  765. }
  766. if (node.init) {
  767. startNewReportsBuffering();
  768. if (hasExcessParens(node.init)) {
  769. report(node.init);
  770. }
  771. }
  772. },
  773. "ForStatement > *.init:exit"(node) {
  774. /*
  775. * Removing parentheses around `in` expressions might change semantics and cause errors.
  776. *
  777. * For example, this valid for loop:
  778. * for (let a = (b in c); ;);
  779. * after removing parentheses would be treated as an invalid for-in loop:
  780. * for (let a = b in c; ;);
  781. */
  782. if (reportsBuffer.reports.length) {
  783. reportsBuffer.inExpressionNodes.forEach(inExpressionNode => {
  784. const path = pathToDescendant(node, inExpressionNode);
  785. let nodeToExclude;
  786. for (let i = 0; i < path.length; i++) {
  787. const pathNode = path[i];
  788. if (i < path.length - 1) {
  789. const nextPathNode = path[i + 1];
  790. if (isSafelyEnclosingInExpression(pathNode, nextPathNode)) {
  791. // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]').
  792. return;
  793. }
  794. }
  795. if (isParenthesised(pathNode)) {
  796. if (isInCurrentReportsBuffer(pathNode)) {
  797. // This node was supposed to be reported, but parentheses might be necessary.
  798. if (isParenthesisedTwice(pathNode)) {
  799. /*
  800. * This node is parenthesised twice, it certainly has at least one pair of `extra` parentheses.
  801. * If the --fix option is on, the current fixing iteration will remove only one pair of parentheses.
  802. * The remaining pair is safely enclosing the 'in' expression.
  803. */
  804. return;
  805. }
  806. // Exclude the outermost node only.
  807. if (!nodeToExclude) {
  808. nodeToExclude = pathNode;
  809. }
  810. // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside.
  811. } else {
  812. // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'.
  813. return;
  814. }
  815. }
  816. }
  817. // Exclude the node from the list (i.e. treat parentheses as necessary)
  818. removeFromCurrentReportsBuffer(nodeToExclude);
  819. });
  820. }
  821. endCurrentReportsBuffering();
  822. },
  823. IfStatement(node) {
  824. if (hasExcessParens(node.test) && !isCondAssignException(node)) {
  825. report(node.test);
  826. }
  827. },
  828. ImportExpression(node) {
  829. const { source } = node;
  830. if (source.type === "SequenceExpression") {
  831. if (hasDoubleExcessParens(source)) {
  832. report(source);
  833. }
  834. } else if (hasExcessParens(source)) {
  835. report(source);
  836. }
  837. },
  838. LogicalExpression: checkBinaryLogical,
  839. MemberExpression(node) {
  840. const shouldAllowWrapOnce = isMemberExpInNewCallee(node) &&
  841. doesMemberExpressionContainCallExpression(node);
  842. const nodeObjHasExcessParens = shouldAllowWrapOnce
  843. ? hasDoubleExcessParens(node.object)
  844. : hasExcessParens(node.object) &&
  845. !(
  846. isImmediateFunctionPrototypeMethodCall(node.parent) &&
  847. node.parent.callee === node &&
  848. IGNORE_FUNCTION_PROTOTYPE_METHODS
  849. );
  850. if (
  851. nodeObjHasExcessParens &&
  852. precedence(node.object) >= precedence(node) &&
  853. (
  854. node.computed ||
  855. !(
  856. astUtils.isDecimalInteger(node.object) ||
  857. // RegExp literal is allowed to have parens (#1589)
  858. (node.object.type === "Literal" && node.object.regex)
  859. )
  860. )
  861. ) {
  862. report(node.object);
  863. }
  864. if (nodeObjHasExcessParens &&
  865. node.object.type === "CallExpression"
  866. ) {
  867. report(node.object);
  868. }
  869. if (nodeObjHasExcessParens &&
  870. !IGNORE_NEW_IN_MEMBER_EXPR &&
  871. node.object.type === "NewExpression" &&
  872. isNewExpressionWithParens(node.object)) {
  873. report(node.object);
  874. }
  875. if (nodeObjHasExcessParens &&
  876. node.optional &&
  877. node.object.type === "ChainExpression"
  878. ) {
  879. report(node.object);
  880. }
  881. if (node.computed && hasExcessParens(node.property)) {
  882. report(node.property);
  883. }
  884. },
  885. NewExpression: checkCallNew,
  886. ObjectExpression(node) {
  887. node.properties
  888. .filter(property => property.value && hasExcessParensWithPrecedence(property.value, PRECEDENCE_OF_ASSIGNMENT_EXPR))
  889. .forEach(property => report(property.value));
  890. },
  891. ObjectPattern(node) {
  892. node.properties
  893. .filter(property => {
  894. const value = property.value;
  895. return canBeAssignmentTarget(value) && hasExcessParens(value);
  896. }).forEach(property => report(property.value));
  897. },
  898. Property(node) {
  899. if (node.computed) {
  900. const { key } = node;
  901. if (key && hasExcessParensWithPrecedence(key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  902. report(key);
  903. }
  904. }
  905. },
  906. RestElement(node) {
  907. const argument = node.argument;
  908. if (canBeAssignmentTarget(argument) && hasExcessParens(argument)) {
  909. report(argument);
  910. }
  911. },
  912. ReturnStatement(node) {
  913. const returnToken = sourceCode.getFirstToken(node);
  914. if (isReturnAssignException(node)) {
  915. return;
  916. }
  917. if (node.argument &&
  918. hasExcessParensNoLineTerminator(returnToken, node.argument) &&
  919. // RegExp literal is allowed to have parens (#1589)
  920. !(node.argument.type === "Literal" && node.argument.regex)) {
  921. report(node.argument);
  922. }
  923. },
  924. SequenceExpression(node) {
  925. const precedenceOfNode = precedence(node);
  926. node.expressions
  927. .filter(e => hasExcessParensWithPrecedence(e, precedenceOfNode))
  928. .forEach(report);
  929. },
  930. SwitchCase(node) {
  931. if (node.test && hasExcessParens(node.test)) {
  932. report(node.test);
  933. }
  934. },
  935. SwitchStatement(node) {
  936. if (hasExcessParens(node.discriminant)) {
  937. report(node.discriminant);
  938. }
  939. },
  940. ThrowStatement(node) {
  941. const throwToken = sourceCode.getFirstToken(node);
  942. if (hasExcessParensNoLineTerminator(throwToken, node.argument)) {
  943. report(node.argument);
  944. }
  945. },
  946. UnaryExpression: checkArgumentWithPrecedence,
  947. UpdateExpression: checkArgumentWithPrecedence,
  948. AwaitExpression: checkArgumentWithPrecedence,
  949. VariableDeclarator(node) {
  950. if (
  951. node.init && hasExcessParensWithPrecedence(node.init, PRECEDENCE_OF_ASSIGNMENT_EXPR) &&
  952. // RegExp literal is allowed to have parens (#1589)
  953. !(node.init.type === "Literal" && node.init.regex)
  954. ) {
  955. report(node.init);
  956. }
  957. },
  958. WhileStatement(node) {
  959. if (hasExcessParens(node.test) && !isCondAssignException(node)) {
  960. report(node.test);
  961. }
  962. },
  963. WithStatement(node) {
  964. if (hasExcessParens(node.object)) {
  965. report(node.object);
  966. }
  967. },
  968. YieldExpression(node) {
  969. if (node.argument) {
  970. const yieldToken = sourceCode.getFirstToken(node);
  971. if ((precedence(node.argument) >= precedence(node) &&
  972. hasExcessParensNoLineTerminator(yieldToken, node.argument)) ||
  973. hasDoubleExcessParens(node.argument)) {
  974. report(node.argument);
  975. }
  976. }
  977. },
  978. ClassDeclaration: checkClass,
  979. ClassExpression: checkClass,
  980. SpreadElement: checkSpreadOperator,
  981. SpreadProperty: checkSpreadOperator,
  982. ExperimentalSpreadProperty: checkSpreadOperator,
  983. TemplateLiteral(node) {
  984. node.expressions
  985. .filter(e => e && hasExcessParens(e))
  986. .forEach(report);
  987. },
  988. AssignmentPattern(node) {
  989. const { left, right } = node;
  990. if (canBeAssignmentTarget(left) && hasExcessParens(left)) {
  991. report(left);
  992. }
  993. if (right && hasExcessParensWithPrecedence(right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  994. report(right);
  995. }
  996. }
  997. };
  998. }
  999. };