Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
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.

no-extra-parens.js 47KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  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. if (
  414. hasDoubleExcessParens(callee) ||
  415. !(
  416. isIIFE(node) ||
  417. // (new A)(); new (new A)();
  418. (
  419. callee.type === "NewExpression" &&
  420. !isNewExpressionWithParens(callee) &&
  421. !(
  422. node.type === "NewExpression" &&
  423. !isNewExpressionWithParens(node)
  424. )
  425. ) ||
  426. // new (a().b)(); new (a.b().c);
  427. (
  428. node.type === "NewExpression" &&
  429. callee.type === "MemberExpression" &&
  430. doesMemberExpressionContainCallExpression(callee)
  431. ) ||
  432. // (a?.b)(); (a?.())();
  433. (
  434. !node.optional &&
  435. callee.type === "ChainExpression"
  436. )
  437. )
  438. ) {
  439. report(node.callee);
  440. }
  441. }
  442. node.arguments
  443. .filter(arg => hasExcessParensWithPrecedence(arg, PRECEDENCE_OF_ASSIGNMENT_EXPR))
  444. .forEach(report);
  445. }
  446. /**
  447. * Evaluate binary logicals
  448. * @param {ASTNode} node node to evaluate
  449. * @returns {void}
  450. * @private
  451. */
  452. function checkBinaryLogical(node) {
  453. const prec = precedence(node);
  454. const leftPrecedence = precedence(node.left);
  455. const rightPrecedence = precedence(node.right);
  456. const isExponentiation = node.operator === "**";
  457. const shouldSkipLeft = NESTED_BINARY && (node.left.type === "BinaryExpression" || node.left.type === "LogicalExpression");
  458. const shouldSkipRight = NESTED_BINARY && (node.right.type === "BinaryExpression" || node.right.type === "LogicalExpression");
  459. if (!shouldSkipLeft && hasExcessParens(node.left)) {
  460. if (
  461. !(["AwaitExpression", "UnaryExpression"].includes(node.left.type) && isExponentiation) &&
  462. !astUtils.isMixedLogicalAndCoalesceExpressions(node.left, node) &&
  463. (leftPrecedence > prec || (leftPrecedence === prec && !isExponentiation)) ||
  464. isParenthesisedTwice(node.left)
  465. ) {
  466. report(node.left);
  467. }
  468. }
  469. if (!shouldSkipRight && hasExcessParens(node.right)) {
  470. if (
  471. !astUtils.isMixedLogicalAndCoalesceExpressions(node.right, node) &&
  472. (rightPrecedence > prec || (rightPrecedence === prec && isExponentiation)) ||
  473. isParenthesisedTwice(node.right)
  474. ) {
  475. report(node.right);
  476. }
  477. }
  478. }
  479. /**
  480. * Check the parentheses around the super class of the given class definition.
  481. * @param {ASTNode} node The node of class declarations to check.
  482. * @returns {void}
  483. */
  484. function checkClass(node) {
  485. if (!node.superClass) {
  486. return;
  487. }
  488. /*
  489. * If `node.superClass` is a LeftHandSideExpression, parentheses are extra.
  490. * Otherwise, parentheses are needed.
  491. */
  492. const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR
  493. ? hasExcessParens(node.superClass)
  494. : hasDoubleExcessParens(node.superClass);
  495. if (hasExtraParens) {
  496. report(node.superClass);
  497. }
  498. }
  499. /**
  500. * Check the parentheses around the argument of the given spread operator.
  501. * @param {ASTNode} node The node of spread elements/properties to check.
  502. * @returns {void}
  503. */
  504. function checkSpreadOperator(node) {
  505. if (hasExcessParensWithPrecedence(node.argument, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  506. report(node.argument);
  507. }
  508. }
  509. /**
  510. * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration
  511. * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node
  512. * @returns {void}
  513. */
  514. function checkExpressionOrExportStatement(node) {
  515. const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node);
  516. const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken);
  517. const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null;
  518. const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null;
  519. if (
  520. astUtils.isOpeningParenToken(firstToken) &&
  521. (
  522. astUtils.isOpeningBraceToken(secondToken) ||
  523. secondToken.type === "Keyword" && (
  524. secondToken.value === "function" ||
  525. secondToken.value === "class" ||
  526. secondToken.value === "let" &&
  527. tokenAfterClosingParens &&
  528. (
  529. astUtils.isOpeningBracketToken(tokenAfterClosingParens) ||
  530. tokenAfterClosingParens.type === "Identifier"
  531. )
  532. ) ||
  533. secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function"
  534. )
  535. ) {
  536. tokensToIgnore.add(secondToken);
  537. }
  538. const hasExtraParens = node.parent.type === "ExportDefaultDeclaration"
  539. ? hasExcessParensWithPrecedence(node, PRECEDENCE_OF_ASSIGNMENT_EXPR)
  540. : hasExcessParens(node);
  541. if (hasExtraParens) {
  542. report(node);
  543. }
  544. }
  545. /**
  546. * Finds the path from the given node to the specified ancestor.
  547. * @param {ASTNode} node First node in the path.
  548. * @param {ASTNode} ancestor Last node in the path.
  549. * @returns {ASTNode[]} Path, including both nodes.
  550. * @throws {Error} If the given node does not have the specified ancestor.
  551. */
  552. function pathToAncestor(node, ancestor) {
  553. const path = [node];
  554. let currentNode = node;
  555. while (currentNode !== ancestor) {
  556. currentNode = currentNode.parent;
  557. /* istanbul ignore if */
  558. if (currentNode === null) {
  559. throw new Error("Nodes are not in the ancestor-descendant relationship.");
  560. }
  561. path.push(currentNode);
  562. }
  563. return path;
  564. }
  565. /**
  566. * Finds the path from the given node to the specified descendant.
  567. * @param {ASTNode} node First node in the path.
  568. * @param {ASTNode} descendant Last node in the path.
  569. * @returns {ASTNode[]} Path, including both nodes.
  570. * @throws {Error} If the given node does not have the specified descendant.
  571. */
  572. function pathToDescendant(node, descendant) {
  573. return pathToAncestor(descendant, node).reverse();
  574. }
  575. /**
  576. * Checks whether the syntax of the given ancestor of an 'in' expression inside a for-loop initializer
  577. * is preventing the 'in' keyword from being interpreted as a part of an ill-formed for-in loop.
  578. * @param {ASTNode} node Ancestor of an 'in' expression.
  579. * @param {ASTNode} child Child of the node, ancestor of the same 'in' expression or the 'in' expression itself.
  580. * @returns {boolean} True if the keyword 'in' would be interpreted as the 'in' operator, without any parenthesis.
  581. */
  582. function isSafelyEnclosingInExpression(node, child) {
  583. switch (node.type) {
  584. case "ArrayExpression":
  585. case "ArrayPattern":
  586. case "BlockStatement":
  587. case "ObjectExpression":
  588. case "ObjectPattern":
  589. case "TemplateLiteral":
  590. return true;
  591. case "ArrowFunctionExpression":
  592. case "FunctionExpression":
  593. return node.params.includes(child);
  594. case "CallExpression":
  595. case "NewExpression":
  596. return node.arguments.includes(child);
  597. case "MemberExpression":
  598. return node.computed && node.property === child;
  599. case "ConditionalExpression":
  600. return node.consequent === child;
  601. default:
  602. return false;
  603. }
  604. }
  605. /**
  606. * Starts a new reports buffering. Warnings will be stored in a buffer instead of being reported immediately.
  607. * An additional logic that requires multiple nodes (e.g. a whole subtree) may dismiss some of the stored warnings.
  608. * @returns {void}
  609. */
  610. function startNewReportsBuffering() {
  611. reportsBuffer = {
  612. upper: reportsBuffer,
  613. inExpressionNodes: [],
  614. reports: []
  615. };
  616. }
  617. /**
  618. * Ends the current reports buffering.
  619. * @returns {void}
  620. */
  621. function endCurrentReportsBuffering() {
  622. const { upper, inExpressionNodes, reports } = reportsBuffer;
  623. if (upper) {
  624. upper.inExpressionNodes.push(...inExpressionNodes);
  625. upper.reports.push(...reports);
  626. } else {
  627. // flush remaining reports
  628. reports.forEach(({ finishReport }) => finishReport());
  629. }
  630. reportsBuffer = upper;
  631. }
  632. /**
  633. * Checks whether the given node is in the current reports buffer.
  634. * @param {ASTNode} node Node to check.
  635. * @returns {boolean} True if the node is in the current buffer, false otherwise.
  636. */
  637. function isInCurrentReportsBuffer(node) {
  638. return reportsBuffer.reports.some(r => r.node === node);
  639. }
  640. /**
  641. * Removes the given node from the current reports buffer.
  642. * @param {ASTNode} node Node to remove.
  643. * @returns {void}
  644. */
  645. function removeFromCurrentReportsBuffer(node) {
  646. reportsBuffer.reports = reportsBuffer.reports.filter(r => r.node !== node);
  647. }
  648. /**
  649. * Checks whether a node is a MemberExpression at NewExpression's callee.
  650. * @param {ASTNode} node node to check.
  651. * @returns {boolean} True if the node is a MemberExpression at NewExpression's callee. false otherwise.
  652. */
  653. function isMemberExpInNewCallee(node) {
  654. if (node.type === "MemberExpression") {
  655. return node.parent.type === "NewExpression" && node.parent.callee === node
  656. ? true
  657. : node.parent.object === node && isMemberExpInNewCallee(node.parent);
  658. }
  659. return false;
  660. }
  661. return {
  662. ArrayExpression(node) {
  663. node.elements
  664. .filter(e => e && hasExcessParensWithPrecedence(e, PRECEDENCE_OF_ASSIGNMENT_EXPR))
  665. .forEach(report);
  666. },
  667. ArrayPattern(node) {
  668. node.elements
  669. .filter(e => canBeAssignmentTarget(e) && hasExcessParens(e))
  670. .forEach(report);
  671. },
  672. ArrowFunctionExpression(node) {
  673. if (isReturnAssignException(node)) {
  674. return;
  675. }
  676. if (node.body.type === "ConditionalExpression" &&
  677. IGNORE_ARROW_CONDITIONALS
  678. ) {
  679. return;
  680. }
  681. if (node.body.type !== "BlockStatement") {
  682. const firstBodyToken = sourceCode.getFirstToken(node.body, astUtils.isNotOpeningParenToken);
  683. const tokenBeforeFirst = sourceCode.getTokenBefore(firstBodyToken);
  684. if (astUtils.isOpeningParenToken(tokenBeforeFirst) && astUtils.isOpeningBraceToken(firstBodyToken)) {
  685. tokensToIgnore.add(firstBodyToken);
  686. }
  687. if (hasExcessParensWithPrecedence(node.body, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  688. report(node.body);
  689. }
  690. }
  691. },
  692. AssignmentExpression(node) {
  693. if (canBeAssignmentTarget(node.left) && hasExcessParens(node.left)) {
  694. report(node.left);
  695. }
  696. if (!isReturnAssignException(node) && hasExcessParensWithPrecedence(node.right, precedence(node))) {
  697. report(node.right);
  698. }
  699. },
  700. BinaryExpression(node) {
  701. if (reportsBuffer && node.operator === "in") {
  702. reportsBuffer.inExpressionNodes.push(node);
  703. }
  704. checkBinaryLogical(node);
  705. },
  706. CallExpression: checkCallNew,
  707. ClassBody(node) {
  708. node.body
  709. .filter(member => member.type === "MethodDefinition" && member.computed && member.key)
  710. .filter(member => hasExcessParensWithPrecedence(member.key, PRECEDENCE_OF_ASSIGNMENT_EXPR))
  711. .forEach(member => report(member.key));
  712. },
  713. ConditionalExpression(node) {
  714. if (isReturnAssignException(node)) {
  715. return;
  716. }
  717. if (
  718. !isCondAssignException(node) &&
  719. hasExcessParensWithPrecedence(node.test, precedence({ type: "LogicalExpression", operator: "||" }))
  720. ) {
  721. report(node.test);
  722. }
  723. if (hasExcessParensWithPrecedence(node.consequent, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  724. report(node.consequent);
  725. }
  726. if (hasExcessParensWithPrecedence(node.alternate, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  727. report(node.alternate);
  728. }
  729. },
  730. DoWhileStatement(node) {
  731. if (hasExcessParens(node.test) && !isCondAssignException(node)) {
  732. report(node.test);
  733. }
  734. },
  735. ExportDefaultDeclaration: node => checkExpressionOrExportStatement(node.declaration),
  736. ExpressionStatement: node => checkExpressionOrExportStatement(node.expression),
  737. ForInStatement(node) {
  738. if (node.left.type !== "VariableDeclaration") {
  739. const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken);
  740. if (
  741. firstLeftToken.value === "let" &&
  742. astUtils.isOpeningBracketToken(
  743. sourceCode.getTokenAfter(firstLeftToken, astUtils.isNotClosingParenToken)
  744. )
  745. ) {
  746. // ForInStatement#left expression cannot start with `let[`.
  747. tokensToIgnore.add(firstLeftToken);
  748. }
  749. }
  750. if (hasExcessParens(node.left)) {
  751. report(node.left);
  752. }
  753. if (hasExcessParens(node.right)) {
  754. report(node.right);
  755. }
  756. },
  757. ForOfStatement(node) {
  758. if (node.left.type !== "VariableDeclaration") {
  759. const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken);
  760. if (firstLeftToken.value === "let") {
  761. // ForOfStatement#left expression cannot start with `let`.
  762. tokensToIgnore.add(firstLeftToken);
  763. }
  764. }
  765. if (hasExcessParens(node.left)) {
  766. report(node.left);
  767. }
  768. if (hasExcessParensWithPrecedence(node.right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  769. report(node.right);
  770. }
  771. },
  772. ForStatement(node) {
  773. if (node.test && hasExcessParens(node.test) && !isCondAssignException(node)) {
  774. report(node.test);
  775. }
  776. if (node.update && hasExcessParens(node.update)) {
  777. report(node.update);
  778. }
  779. if (node.init) {
  780. if (node.init.type !== "VariableDeclaration") {
  781. const firstToken = sourceCode.getFirstToken(node.init, astUtils.isNotOpeningParenToken);
  782. if (
  783. firstToken.value === "let" &&
  784. astUtils.isOpeningBracketToken(
  785. sourceCode.getTokenAfter(firstToken, astUtils.isNotClosingParenToken)
  786. )
  787. ) {
  788. // ForStatement#init expression cannot start with `let[`.
  789. tokensToIgnore.add(firstToken);
  790. }
  791. }
  792. startNewReportsBuffering();
  793. if (hasExcessParens(node.init)) {
  794. report(node.init);
  795. }
  796. }
  797. },
  798. "ForStatement > *.init:exit"(node) {
  799. /*
  800. * Removing parentheses around `in` expressions might change semantics and cause errors.
  801. *
  802. * For example, this valid for loop:
  803. * for (let a = (b in c); ;);
  804. * after removing parentheses would be treated as an invalid for-in loop:
  805. * for (let a = b in c; ;);
  806. */
  807. if (reportsBuffer.reports.length) {
  808. reportsBuffer.inExpressionNodes.forEach(inExpressionNode => {
  809. const path = pathToDescendant(node, inExpressionNode);
  810. let nodeToExclude;
  811. for (let i = 0; i < path.length; i++) {
  812. const pathNode = path[i];
  813. if (i < path.length - 1) {
  814. const nextPathNode = path[i + 1];
  815. if (isSafelyEnclosingInExpression(pathNode, nextPathNode)) {
  816. // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]').
  817. return;
  818. }
  819. }
  820. if (isParenthesised(pathNode)) {
  821. if (isInCurrentReportsBuffer(pathNode)) {
  822. // This node was supposed to be reported, but parentheses might be necessary.
  823. if (isParenthesisedTwice(pathNode)) {
  824. /*
  825. * This node is parenthesised twice, it certainly has at least one pair of `extra` parentheses.
  826. * If the --fix option is on, the current fixing iteration will remove only one pair of parentheses.
  827. * The remaining pair is safely enclosing the 'in' expression.
  828. */
  829. return;
  830. }
  831. // Exclude the outermost node only.
  832. if (!nodeToExclude) {
  833. nodeToExclude = pathNode;
  834. }
  835. // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside.
  836. } else {
  837. // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'.
  838. return;
  839. }
  840. }
  841. }
  842. // Exclude the node from the list (i.e. treat parentheses as necessary)
  843. removeFromCurrentReportsBuffer(nodeToExclude);
  844. });
  845. }
  846. endCurrentReportsBuffering();
  847. },
  848. IfStatement(node) {
  849. if (hasExcessParens(node.test) && !isCondAssignException(node)) {
  850. report(node.test);
  851. }
  852. },
  853. ImportExpression(node) {
  854. const { source } = node;
  855. if (source.type === "SequenceExpression") {
  856. if (hasDoubleExcessParens(source)) {
  857. report(source);
  858. }
  859. } else if (hasExcessParens(source)) {
  860. report(source);
  861. }
  862. },
  863. LogicalExpression: checkBinaryLogical,
  864. MemberExpression(node) {
  865. const shouldAllowWrapOnce = isMemberExpInNewCallee(node) &&
  866. doesMemberExpressionContainCallExpression(node);
  867. const nodeObjHasExcessParens = shouldAllowWrapOnce
  868. ? hasDoubleExcessParens(node.object)
  869. : hasExcessParens(node.object) &&
  870. !(
  871. isImmediateFunctionPrototypeMethodCall(node.parent) &&
  872. node.parent.callee === node &&
  873. IGNORE_FUNCTION_PROTOTYPE_METHODS
  874. );
  875. if (
  876. nodeObjHasExcessParens &&
  877. precedence(node.object) >= precedence(node) &&
  878. (
  879. node.computed ||
  880. !(
  881. astUtils.isDecimalInteger(node.object) ||
  882. // RegExp literal is allowed to have parens (#1589)
  883. (node.object.type === "Literal" && node.object.regex)
  884. )
  885. )
  886. ) {
  887. report(node.object);
  888. }
  889. if (nodeObjHasExcessParens &&
  890. node.object.type === "CallExpression"
  891. ) {
  892. report(node.object);
  893. }
  894. if (nodeObjHasExcessParens &&
  895. !IGNORE_NEW_IN_MEMBER_EXPR &&
  896. node.object.type === "NewExpression" &&
  897. isNewExpressionWithParens(node.object)) {
  898. report(node.object);
  899. }
  900. if (nodeObjHasExcessParens &&
  901. node.optional &&
  902. node.object.type === "ChainExpression"
  903. ) {
  904. report(node.object);
  905. }
  906. if (node.computed && hasExcessParens(node.property)) {
  907. report(node.property);
  908. }
  909. },
  910. NewExpression: checkCallNew,
  911. ObjectExpression(node) {
  912. node.properties
  913. .filter(property => property.value && hasExcessParensWithPrecedence(property.value, PRECEDENCE_OF_ASSIGNMENT_EXPR))
  914. .forEach(property => report(property.value));
  915. },
  916. ObjectPattern(node) {
  917. node.properties
  918. .filter(property => {
  919. const value = property.value;
  920. return canBeAssignmentTarget(value) && hasExcessParens(value);
  921. }).forEach(property => report(property.value));
  922. },
  923. Property(node) {
  924. if (node.computed) {
  925. const { key } = node;
  926. if (key && hasExcessParensWithPrecedence(key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  927. report(key);
  928. }
  929. }
  930. },
  931. RestElement(node) {
  932. const argument = node.argument;
  933. if (canBeAssignmentTarget(argument) && hasExcessParens(argument)) {
  934. report(argument);
  935. }
  936. },
  937. ReturnStatement(node) {
  938. const returnToken = sourceCode.getFirstToken(node);
  939. if (isReturnAssignException(node)) {
  940. return;
  941. }
  942. if (node.argument &&
  943. hasExcessParensNoLineTerminator(returnToken, node.argument) &&
  944. // RegExp literal is allowed to have parens (#1589)
  945. !(node.argument.type === "Literal" && node.argument.regex)) {
  946. report(node.argument);
  947. }
  948. },
  949. SequenceExpression(node) {
  950. const precedenceOfNode = precedence(node);
  951. node.expressions
  952. .filter(e => hasExcessParensWithPrecedence(e, precedenceOfNode))
  953. .forEach(report);
  954. },
  955. SwitchCase(node) {
  956. if (node.test && hasExcessParens(node.test)) {
  957. report(node.test);
  958. }
  959. },
  960. SwitchStatement(node) {
  961. if (hasExcessParens(node.discriminant)) {
  962. report(node.discriminant);
  963. }
  964. },
  965. ThrowStatement(node) {
  966. const throwToken = sourceCode.getFirstToken(node);
  967. if (hasExcessParensNoLineTerminator(throwToken, node.argument)) {
  968. report(node.argument);
  969. }
  970. },
  971. UnaryExpression: checkArgumentWithPrecedence,
  972. UpdateExpression(node) {
  973. if (node.prefix) {
  974. checkArgumentWithPrecedence(node);
  975. } else {
  976. const { argument } = node;
  977. const operatorToken = sourceCode.getLastToken(node);
  978. if (argument.loc.end.line === operatorToken.loc.start.line) {
  979. checkArgumentWithPrecedence(node);
  980. } else {
  981. if (hasDoubleExcessParens(argument)) {
  982. report(argument);
  983. }
  984. }
  985. }
  986. },
  987. AwaitExpression: checkArgumentWithPrecedence,
  988. VariableDeclarator(node) {
  989. if (
  990. node.init && hasExcessParensWithPrecedence(node.init, PRECEDENCE_OF_ASSIGNMENT_EXPR) &&
  991. // RegExp literal is allowed to have parens (#1589)
  992. !(node.init.type === "Literal" && node.init.regex)
  993. ) {
  994. report(node.init);
  995. }
  996. },
  997. WhileStatement(node) {
  998. if (hasExcessParens(node.test) && !isCondAssignException(node)) {
  999. report(node.test);
  1000. }
  1001. },
  1002. WithStatement(node) {
  1003. if (hasExcessParens(node.object)) {
  1004. report(node.object);
  1005. }
  1006. },
  1007. YieldExpression(node) {
  1008. if (node.argument) {
  1009. const yieldToken = sourceCode.getFirstToken(node);
  1010. if ((precedence(node.argument) >= precedence(node) &&
  1011. hasExcessParensNoLineTerminator(yieldToken, node.argument)) ||
  1012. hasDoubleExcessParens(node.argument)) {
  1013. report(node.argument);
  1014. }
  1015. }
  1016. },
  1017. ClassDeclaration: checkClass,
  1018. ClassExpression: checkClass,
  1019. SpreadElement: checkSpreadOperator,
  1020. SpreadProperty: checkSpreadOperator,
  1021. ExperimentalSpreadProperty: checkSpreadOperator,
  1022. TemplateLiteral(node) {
  1023. node.expressions
  1024. .filter(e => e && hasExcessParens(e))
  1025. .forEach(report);
  1026. },
  1027. AssignmentPattern(node) {
  1028. const { left, right } = node;
  1029. if (canBeAssignmentTarget(left) && hasExcessParens(left)) {
  1030. report(left);
  1031. }
  1032. if (right && hasExcessParensWithPrecedence(right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
  1033. report(right);
  1034. }
  1035. }
  1036. };
  1037. }
  1038. };