no-extra-parens.js 40 KB

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