no-extra-parens.js 48 KB

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