eslint 9.22.0 → 9.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (417) hide show
  1. package/README.md +48 -46
  2. package/bin/eslint.js +92 -90
  3. package/conf/default-cli-options.js +22 -22
  4. package/conf/ecma-version.js +1 -1
  5. package/conf/globals.js +97 -98
  6. package/conf/replacements.json +24 -20
  7. package/conf/rule-type-list.json +88 -92
  8. package/lib/api.js +12 -12
  9. package/lib/cli-engine/cli-engine.js +830 -810
  10. package/lib/cli-engine/file-enumerator.js +381 -387
  11. package/lib/cli-engine/formatters/formatters-meta.json +16 -16
  12. package/lib/cli-engine/formatters/html.js +107 -99
  13. package/lib/cli-engine/formatters/json-with-metadata.js +5 -5
  14. package/lib/cli-engine/formatters/json.js +2 -2
  15. package/lib/cli-engine/formatters/stylish.js +96 -75
  16. package/lib/cli-engine/hash.js +1 -1
  17. package/lib/cli-engine/index.js +1 -1
  18. package/lib/cli-engine/lint-result-cache.js +144 -145
  19. package/lib/cli-engine/load-rules.js +16 -16
  20. package/lib/cli.js +638 -457
  21. package/lib/config/config-loader.js +726 -622
  22. package/lib/config/config.js +247 -221
  23. package/lib/config/default-config.js +54 -45
  24. package/lib/config/flat-config-array.js +167 -172
  25. package/lib/config/flat-config-helpers.js +72 -72
  26. package/lib/config/flat-config-schema.js +375 -368
  27. package/lib/config/rule-validator.js +139 -144
  28. package/lib/config-api.js +2 -2
  29. package/lib/eslint/eslint-helpers.js +756 -681
  30. package/lib/eslint/eslint.js +934 -912
  31. package/lib/eslint/index.js +2 -2
  32. package/lib/eslint/legacy-eslint.js +577 -533
  33. package/lib/languages/js/index.js +263 -264
  34. package/lib/languages/js/source-code/index.js +1 -1
  35. package/lib/languages/js/source-code/source-code.js +1128 -1057
  36. package/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js +39 -35
  37. package/lib/languages/js/source-code/token-store/backward-token-cursor.js +35 -36
  38. package/lib/languages/js/source-code/token-store/cursor.js +36 -36
  39. package/lib/languages/js/source-code/token-store/cursors.js +80 -52
  40. package/lib/languages/js/source-code/token-store/decorative-cursor.js +17 -18
  41. package/lib/languages/js/source-code/token-store/filter-cursor.js +19 -20
  42. package/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js +40 -32
  43. package/lib/languages/js/source-code/token-store/forward-token-cursor.js +40 -41
  44. package/lib/languages/js/source-code/token-store/index.js +592 -498
  45. package/lib/languages/js/source-code/token-store/limit-cursor.js +17 -18
  46. package/lib/languages/js/source-code/token-store/padded-token-cursor.js +23 -16
  47. package/lib/languages/js/source-code/token-store/skip-cursor.js +19 -20
  48. package/lib/languages/js/source-code/token-store/utils.js +63 -60
  49. package/lib/languages/js/validate-language-options.js +104 -89
  50. package/lib/linter/apply-disable-directives.js +467 -383
  51. package/lib/linter/code-path-analysis/code-path-analyzer.js +650 -672
  52. package/lib/linter/code-path-analysis/code-path-segment.js +215 -216
  53. package/lib/linter/code-path-analysis/code-path-state.js +2118 -2096
  54. package/lib/linter/code-path-analysis/code-path.js +307 -319
  55. package/lib/linter/code-path-analysis/debug-helpers.js +183 -163
  56. package/lib/linter/code-path-analysis/fork-context.js +296 -271
  57. package/lib/linter/code-path-analysis/id-generator.js +22 -23
  58. package/lib/linter/file-context.js +119 -120
  59. package/lib/linter/index.js +3 -3
  60. package/lib/linter/interpolate.js +16 -16
  61. package/lib/linter/linter.js +2403 -2045
  62. package/lib/linter/node-event-generator.js +284 -225
  63. package/lib/linter/report-translator.js +256 -219
  64. package/lib/linter/rule-fixer.js +122 -124
  65. package/lib/linter/rules.js +36 -36
  66. package/lib/linter/safe-emitter.js +18 -18
  67. package/lib/linter/source-code-fixer.js +94 -92
  68. package/lib/linter/timing.js +104 -101
  69. package/lib/linter/vfile.js +70 -73
  70. package/lib/options.js +404 -361
  71. package/lib/rule-tester/index.js +1 -1
  72. package/lib/rule-tester/rule-tester.js +1308 -1046
  73. package/lib/rules/accessor-pairs.js +298 -263
  74. package/lib/rules/array-bracket-newline.js +250 -238
  75. package/lib/rules/array-bracket-spacing.js +263 -224
  76. package/lib/rules/array-callback-return.js +402 -356
  77. package/lib/rules/array-element-newline.js +358 -313
  78. package/lib/rules/arrow-body-style.js +400 -281
  79. package/lib/rules/arrow-parens.js +206 -173
  80. package/lib/rules/arrow-spacing.js +169 -163
  81. package/lib/rules/block-scoped-var.js +125 -123
  82. package/lib/rules/block-spacing.js +186 -176
  83. package/lib/rules/brace-style.js +262 -199
  84. package/lib/rules/callback-return.js +203 -190
  85. package/lib/rules/camelcase.js +403 -392
  86. package/lib/rules/capitalized-comments.js +253 -232
  87. package/lib/rules/class-methods-use-this.js +224 -172
  88. package/lib/rules/comma-dangle.js +379 -346
  89. package/lib/rules/comma-spacing.js +193 -195
  90. package/lib/rules/comma-style.js +375 -316
  91. package/lib/rules/complexity.js +173 -169
  92. package/lib/rules/computed-property-spacing.js +236 -211
  93. package/lib/rules/consistent-return.js +181 -170
  94. package/lib/rules/consistent-this.js +167 -147
  95. package/lib/rules/constructor-super.js +412 -404
  96. package/lib/rules/curly.js +407 -332
  97. package/lib/rules/default-case-last.js +38 -31
  98. package/lib/rules/default-case.js +89 -85
  99. package/lib/rules/default-param-last.js +69 -54
  100. package/lib/rules/dot-location.js +122 -110
  101. package/lib/rules/dot-notation.js +192 -156
  102. package/lib/rules/eol-last.js +122 -120
  103. package/lib/rules/eqeqeq.js +168 -155
  104. package/lib/rules/for-direction.js +146 -121
  105. package/lib/rules/func-call-spacing.js +261 -231
  106. package/lib/rules/func-name-matching.js +293 -209
  107. package/lib/rules/func-names.js +165 -164
  108. package/lib/rules/func-style.js +159 -127
  109. package/lib/rules/function-call-argument-newline.js +152 -129
  110. package/lib/rules/function-paren-newline.js +349 -291
  111. package/lib/rules/generator-star-spacing.js +229 -210
  112. package/lib/rules/getter-return.js +208 -172
  113. package/lib/rules/global-require.js +85 -74
  114. package/lib/rules/grouped-accessor-pairs.js +170 -150
  115. package/lib/rules/guard-for-in.js +72 -63
  116. package/lib/rules/handle-callback-err.js +108 -103
  117. package/lib/rules/id-blacklist.js +182 -199
  118. package/lib/rules/id-denylist.js +168 -187
  119. package/lib/rules/id-length.js +197 -171
  120. package/lib/rules/id-match.js +344 -289
  121. package/lib/rules/implicit-arrow-linebreak.js +102 -79
  122. package/lib/rules/indent-legacy.js +1344 -1118
  123. package/lib/rules/indent.js +2272 -1759
  124. package/lib/rules/index.js +317 -292
  125. package/lib/rules/init-declarations.js +137 -107
  126. package/lib/rules/jsx-quotes.js +94 -82
  127. package/lib/rules/key-spacing.js +750 -633
  128. package/lib/rules/keyword-spacing.js +648 -605
  129. package/lib/rules/line-comment-position.js +142 -128
  130. package/lib/rules/linebreak-style.js +107 -106
  131. package/lib/rules/lines-around-comment.js +540 -448
  132. package/lib/rules/lines-around-directive.js +233 -203
  133. package/lib/rules/lines-between-class-members.js +305 -234
  134. package/lib/rules/logical-assignment-operators.js +582 -399
  135. package/lib/rules/max-classes-per-file.js +69 -68
  136. package/lib/rules/max-depth.js +146 -143
  137. package/lib/rules/max-len.js +473 -434
  138. package/lib/rules/max-lines-per-function.js +201 -176
  139. package/lib/rules/max-lines.js +158 -162
  140. package/lib/rules/max-nested-callbacks.js +102 -104
  141. package/lib/rules/max-params.js +78 -76
  142. package/lib/rules/max-statements-per-line.js +205 -198
  143. package/lib/rules/max-statements.js +168 -164
  144. package/lib/rules/multiline-comment-style.js +637 -479
  145. package/lib/rules/multiline-ternary.js +241 -176
  146. package/lib/rules/new-cap.js +233 -213
  147. package/lib/rules/new-parens.js +88 -79
  148. package/lib/rules/newline-after-var.js +287 -250
  149. package/lib/rules/newline-before-return.js +229 -222
  150. package/lib/rules/newline-per-chained-call.js +142 -127
  151. package/lib/rules/no-alert.js +90 -79
  152. package/lib/rules/no-array-constructor.js +125 -113
  153. package/lib/rules/no-async-promise-executor.js +30 -24
  154. package/lib/rules/no-await-in-loop.js +69 -71
  155. package/lib/rules/no-bitwise.js +124 -100
  156. package/lib/rules/no-buffer-constructor.js +55 -47
  157. package/lib/rules/no-caller.js +39 -33
  158. package/lib/rules/no-case-declarations.js +61 -57
  159. package/lib/rules/no-catch-shadow.js +76 -73
  160. package/lib/rules/no-class-assign.js +51 -48
  161. package/lib/rules/no-compare-neg-zero.js +62 -48
  162. package/lib/rules/no-cond-assign.js +148 -132
  163. package/lib/rules/no-confusing-arrow.js +98 -81
  164. package/lib/rules/no-console.js +202 -199
  165. package/lib/rules/no-const-assign.js +47 -41
  166. package/lib/rules/no-constant-binary-expression.js +500 -405
  167. package/lib/rules/no-constant-condition.js +158 -143
  168. package/lib/rules/no-constructor-return.js +49 -49
  169. package/lib/rules/no-continue.js +25 -27
  170. package/lib/rules/no-control-regex.js +125 -121
  171. package/lib/rules/no-debugger.js +28 -30
  172. package/lib/rules/no-delete-var.js +29 -29
  173. package/lib/rules/no-div-regex.js +47 -41
  174. package/lib/rules/no-dupe-args.js +68 -69
  175. package/lib/rules/no-dupe-class-members.js +102 -89
  176. package/lib/rules/no-dupe-else-if.js +100 -77
  177. package/lib/rules/no-dupe-keys.js +133 -110
  178. package/lib/rules/no-duplicate-case.js +50 -43
  179. package/lib/rules/no-duplicate-imports.js +179 -176
  180. package/lib/rules/no-else-return.js +430 -385
  181. package/lib/rules/no-empty-character-class.js +57 -50
  182. package/lib/rules/no-empty-function.js +127 -128
  183. package/lib/rules/no-empty-pattern.js +63 -58
  184. package/lib/rules/no-empty-static-block.js +37 -35
  185. package/lib/rules/no-empty.js +98 -86
  186. package/lib/rules/no-eq-null.js +37 -32
  187. package/lib/rules/no-eval.js +256 -250
  188. package/lib/rules/no-ex-assign.js +42 -39
  189. package/lib/rules/no-extend-native.js +161 -159
  190. package/lib/rules/no-extra-bind.js +201 -190
  191. package/lib/rules/no-extra-boolean-cast.js +398 -348
  192. package/lib/rules/no-extra-label.js +150 -131
  193. package/lib/rules/no-extra-parens.js +1654 -1325
  194. package/lib/rules/no-extra-semi.js +146 -144
  195. package/lib/rules/no-fallthrough.js +199 -157
  196. package/lib/rules/no-floating-decimal.js +74 -66
  197. package/lib/rules/no-func-assign.js +54 -55
  198. package/lib/rules/no-global-assign.js +78 -73
  199. package/lib/rules/no-implicit-coercion.js +349 -293
  200. package/lib/rules/no-implicit-globals.js +158 -135
  201. package/lib/rules/no-implied-eval.js +140 -112
  202. package/lib/rules/no-import-assign.js +145 -159
  203. package/lib/rules/no-inline-comments.js +101 -95
  204. package/lib/rules/no-inner-declarations.js +115 -101
  205. package/lib/rules/no-invalid-regexp.js +222 -190
  206. package/lib/rules/no-invalid-this.js +123 -117
  207. package/lib/rules/no-irregular-whitespace.js +266 -252
  208. package/lib/rules/no-iterator.js +29 -33
  209. package/lib/rules/no-label-var.js +59 -62
  210. package/lib/rules/no-labels.js +138 -133
  211. package/lib/rules/no-lone-blocks.js +127 -123
  212. package/lib/rules/no-lonely-if.js +108 -77
  213. package/lib/rules/no-loop-func.js +238 -213
  214. package/lib/rules/no-loss-of-precision.js +218 -201
  215. package/lib/rules/no-magic-numbers.js +246 -218
  216. package/lib/rules/no-misleading-character-class.js +499 -446
  217. package/lib/rules/no-mixed-operators.js +188 -182
  218. package/lib/rules/no-mixed-requires.js +253 -240
  219. package/lib/rules/no-mixed-spaces-and-tabs.js +134 -121
  220. package/lib/rules/no-multi-assign.js +46 -44
  221. package/lib/rules/no-multi-spaces.js +163 -143
  222. package/lib/rules/no-multi-str.js +42 -41
  223. package/lib/rules/no-multiple-empty-lines.js +196 -158
  224. package/lib/rules/no-native-reassign.js +90 -85
  225. package/lib/rules/no-negated-condition.js +79 -75
  226. package/lib/rules/no-negated-in-lhs.js +45 -43
  227. package/lib/rules/no-nested-ternary.js +33 -32
  228. package/lib/rules/no-new-func.js +71 -62
  229. package/lib/rules/no-new-native-nonconstructor.js +43 -39
  230. package/lib/rules/no-new-object.js +48 -48
  231. package/lib/rules/no-new-require.js +48 -47
  232. package/lib/rules/no-new-symbol.js +52 -50
  233. package/lib/rules/no-new-wrappers.js +43 -41
  234. package/lib/rules/no-new.js +28 -29
  235. package/lib/rules/no-nonoctal-decimal-escape.js +141 -121
  236. package/lib/rules/no-obj-calls.js +66 -53
  237. package/lib/rules/no-object-constructor.js +104 -97
  238. package/lib/rules/no-octal-escape.js +40 -43
  239. package/lib/rules/no-octal.js +32 -32
  240. package/lib/rules/no-param-reassign.js +235 -217
  241. package/lib/rules/no-path-concat.js +66 -67
  242. package/lib/rules/no-plusplus.js +60 -61
  243. package/lib/rules/no-process-env.js +49 -48
  244. package/lib/rules/no-process-exit.js +54 -50
  245. package/lib/rules/no-promise-executor-return.js +214 -182
  246. package/lib/rules/no-proto.js +26 -29
  247. package/lib/rules/no-prototype-builtins.js +146 -124
  248. package/lib/rules/no-redeclare.js +154 -152
  249. package/lib/rules/no-regex-spaces.js +183 -161
  250. package/lib/rules/no-restricted-exports.js +208 -185
  251. package/lib/rules/no-restricted-globals.js +111 -112
  252. package/lib/rules/no-restricted-imports.js +657 -537
  253. package/lib/rules/no-restricted-modules.js +222 -202
  254. package/lib/rules/no-restricted-properties.js +181 -153
  255. package/lib/rules/no-restricted-syntax.js +56 -52
  256. package/lib/rules/no-return-assign.js +55 -50
  257. package/lib/rules/no-return-await.js +148 -124
  258. package/lib/rules/no-script-url.js +52 -45
  259. package/lib/rules/no-self-assign.js +148 -146
  260. package/lib/rules/no-self-compare.js +63 -46
  261. package/lib/rules/no-sequences.js +135 -116
  262. package/lib/rules/no-setter-return.js +185 -152
  263. package/lib/rules/no-shadow-restricted-names.js +61 -46
  264. package/lib/rules/no-shadow.js +342 -316
  265. package/lib/rules/no-spaced-func.js +82 -77
  266. package/lib/rules/no-sparse-arrays.js +54 -59
  267. package/lib/rules/no-sync.js +61 -60
  268. package/lib/rules/no-tabs.js +83 -72
  269. package/lib/rules/no-template-curly-in-string.js +33 -32
  270. package/lib/rules/no-ternary.js +25 -29
  271. package/lib/rules/no-this-before-super.js +321 -319
  272. package/lib/rules/no-throw-literal.js +31 -36
  273. package/lib/rules/no-trailing-spaces.js +199 -191
  274. package/lib/rules/no-undef-init.js +76 -61
  275. package/lib/rules/no-undef.js +51 -48
  276. package/lib/rules/no-undefined.js +73 -75
  277. package/lib/rules/no-underscore-dangle.js +370 -327
  278. package/lib/rules/no-unexpected-multiline.js +112 -102
  279. package/lib/rules/no-unmodified-loop-condition.js +254 -254
  280. package/lib/rules/no-unneeded-ternary.js +212 -147
  281. package/lib/rules/no-unreachable-loop.js +145 -142
  282. package/lib/rules/no-unreachable.js +255 -248
  283. package/lib/rules/no-unsafe-finally.js +93 -85
  284. package/lib/rules/no-unsafe-negation.js +105 -83
  285. package/lib/rules/no-unsafe-optional-chaining.js +192 -178
  286. package/lib/rules/no-unused-expressions.js +178 -162
  287. package/lib/rules/no-unused-labels.js +139 -124
  288. package/lib/rules/no-unused-private-class-members.js +206 -182
  289. package/lib/rules/no-unused-vars.js +1669 -1449
  290. package/lib/rules/no-use-before-define.js +229 -231
  291. package/lib/rules/no-useless-assignment.js +590 -511
  292. package/lib/rules/no-useless-backreference.js +212 -193
  293. package/lib/rules/no-useless-call.js +58 -53
  294. package/lib/rules/no-useless-catch.js +40 -40
  295. package/lib/rules/no-useless-computed-key.js +144 -115
  296. package/lib/rules/no-useless-concat.js +65 -60
  297. package/lib/rules/no-useless-constructor.js +158 -111
  298. package/lib/rules/no-useless-escape.js +342 -291
  299. package/lib/rules/no-useless-rename.js +183 -156
  300. package/lib/rules/no-useless-return.js +344 -312
  301. package/lib/rules/no-var.js +233 -212
  302. package/lib/rules/no-void.js +50 -48
  303. package/lib/rules/no-warning-comments.js +191 -186
  304. package/lib/rules/no-whitespace-before-property.js +131 -115
  305. package/lib/rules/no-with.js +24 -26
  306. package/lib/rules/nonblock-statement-body-position.js +149 -130
  307. package/lib/rules/object-curly-newline.js +306 -265
  308. package/lib/rules/object-curly-spacing.js +360 -314
  309. package/lib/rules/object-property-newline.js +137 -106
  310. package/lib/rules/object-shorthand.js +607 -502
  311. package/lib/rules/one-var-declaration-per-line.js +104 -100
  312. package/lib/rules/one-var.js +653 -537
  313. package/lib/rules/operator-assignment.js +219 -161
  314. package/lib/rules/operator-linebreak.js +295 -251
  315. package/lib/rules/padded-blocks.js +346 -308
  316. package/lib/rules/padding-line-between-statements.js +443 -439
  317. package/lib/rules/prefer-arrow-callback.js +362 -313
  318. package/lib/rules/prefer-const.js +418 -377
  319. package/lib/rules/prefer-destructuring.js +301 -279
  320. package/lib/rules/prefer-exponentiation-operator.js +176 -133
  321. package/lib/rules/prefer-named-capture-group.js +153 -140
  322. package/lib/rules/prefer-numeric-literals.js +121 -113
  323. package/lib/rules/prefer-object-has-own.js +116 -82
  324. package/lib/rules/prefer-object-spread.js +213 -193
  325. package/lib/rules/prefer-promise-reject-errors.js +140 -122
  326. package/lib/rules/prefer-reflect.js +127 -107
  327. package/lib/rules/prefer-regex-literals.js +578 -466
  328. package/lib/rules/prefer-rest-params.js +79 -80
  329. package/lib/rules/prefer-spread.js +47 -44
  330. package/lib/rules/prefer-template.js +266 -195
  331. package/lib/rules/quote-props.js +373 -307
  332. package/lib/rules/quotes.js +374 -326
  333. package/lib/rules/radix.js +152 -136
  334. package/lib/rules/require-atomic-updates.js +316 -285
  335. package/lib/rules/require-await.js +144 -116
  336. package/lib/rules/require-unicode-regexp.js +282 -177
  337. package/lib/rules/require-yield.js +53 -54
  338. package/lib/rules/rest-spread-spacing.js +128 -116
  339. package/lib/rules/semi-spacing.js +281 -250
  340. package/lib/rules/semi-style.js +176 -134
  341. package/lib/rules/semi.js +456 -436
  342. package/lib/rules/sort-imports.js +306 -233
  343. package/lib/rules/sort-keys.js +219 -188
  344. package/lib/rules/sort-vars.js +127 -93
  345. package/lib/rules/space-before-blocks.js +199 -189
  346. package/lib/rules/space-before-function-paren.js +186 -166
  347. package/lib/rules/space-in-parens.js +359 -288
  348. package/lib/rules/space-infix-ops.js +237 -201
  349. package/lib/rules/space-unary-ops.js +356 -298
  350. package/lib/rules/spaced-comment.js +363 -319
  351. package/lib/rules/strict.js +265 -230
  352. package/lib/rules/switch-colon-spacing.js +130 -122
  353. package/lib/rules/symbol-description.js +45 -48
  354. package/lib/rules/template-curly-spacing.js +148 -142
  355. package/lib/rules/template-tag-spacing.js +98 -88
  356. package/lib/rules/unicode-bom.js +54 -56
  357. package/lib/rules/use-isnan.js +237 -206
  358. package/lib/rules/utils/ast-utils.js +2039 -1860
  359. package/lib/rules/utils/char-source.js +162 -155
  360. package/lib/rules/utils/fix-tracker.js +83 -80
  361. package/lib/rules/utils/keywords.js +59 -59
  362. package/lib/rules/utils/lazy-loading-rule-map.js +79 -76
  363. package/lib/rules/utils/regular-expressions.js +32 -24
  364. package/lib/rules/utils/unicode/index.js +4 -4
  365. package/lib/rules/utils/unicode/is-combining-character.js +1 -1
  366. package/lib/rules/utils/unicode/is-emoji-modifier.js +1 -1
  367. package/lib/rules/utils/unicode/is-regional-indicator-symbol.js +1 -1
  368. package/lib/rules/utils/unicode/is-surrogate-pair.js +1 -1
  369. package/lib/rules/valid-typeof.js +153 -111
  370. package/lib/rules/vars-on-top.js +152 -145
  371. package/lib/rules/wrap-iife.js +204 -191
  372. package/lib/rules/wrap-regex.js +70 -58
  373. package/lib/rules/yield-star-spacing.js +145 -134
  374. package/lib/rules/yoda.js +283 -272
  375. package/lib/services/parser-service.js +35 -35
  376. package/lib/services/processor-service.js +66 -73
  377. package/lib/services/suppressions-service.js +289 -0
  378. package/lib/shared/ajv.js +14 -14
  379. package/lib/shared/assert.js +3 -4
  380. package/lib/shared/ast-utils.js +7 -6
  381. package/lib/shared/deep-merge-arrays.js +24 -22
  382. package/lib/shared/directives.js +3 -2
  383. package/lib/shared/flags.js +50 -17
  384. package/lib/shared/logging.js +24 -25
  385. package/lib/shared/option-utils.js +43 -36
  386. package/lib/shared/runtime-info.js +136 -127
  387. package/lib/shared/serialization.js +27 -27
  388. package/lib/shared/severity.js +22 -22
  389. package/lib/shared/stats.js +5 -5
  390. package/lib/shared/string-utils.js +16 -16
  391. package/lib/shared/text-table.js +28 -27
  392. package/lib/shared/traverser.js +153 -146
  393. package/lib/shared/types.js +4 -27
  394. package/lib/types/index.d.ts +2010 -1559
  395. package/lib/types/rules.d.ts +5253 -5140
  396. package/lib/types/use-at-your-own-risk.d.ts +32 -30
  397. package/lib/unsupported-api.js +5 -5
  398. package/messages/all-files-ignored.js +3 -3
  399. package/messages/all-matched-files-ignored.js +3 -3
  400. package/messages/config-file-missing.js +2 -2
  401. package/messages/config-plugin-missing.js +3 -3
  402. package/messages/config-serialize-function.js +9 -7
  403. package/messages/eslintrc-incompat.js +13 -15
  404. package/messages/eslintrc-plugins.js +3 -4
  405. package/messages/extend-config-missing.js +3 -3
  406. package/messages/failed-to-read-json.js +3 -3
  407. package/messages/file-not-found.js +3 -3
  408. package/messages/invalid-rule-options.js +2 -2
  409. package/messages/invalid-rule-severity.js +2 -2
  410. package/messages/no-config-found.js +3 -3
  411. package/messages/plugin-conflict.js +8 -8
  412. package/messages/plugin-invalid.js +3 -3
  413. package/messages/plugin-missing.js +3 -3
  414. package/messages/print-config-with-directory-path.js +2 -2
  415. package/messages/shared.js +6 -1
  416. package/messages/whitespace-found.js +3 -3
  417. package/package.json +14 -20
@@ -9,1332 +9,1661 @@
9
9
  // Rule Definition
10
10
  //------------------------------------------------------------------------------
11
11
 
12
- const { isParenthesized: isParenthesizedRaw } = require("@eslint-community/eslint-utils");
12
+ const {
13
+ isParenthesized: isParenthesizedRaw,
14
+ } = require("@eslint-community/eslint-utils");
13
15
  const astUtils = require("./utils/ast-utils.js");
14
16
 
15
- /** @type {import('../shared/types').Rule} */
17
+ /** @type {import('../types').Rule.RuleModule} */
16
18
  module.exports = {
17
- meta: {
18
- deprecated: {
19
- message: "Formatting rules are being moved out of ESLint core.",
20
- url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
21
- deprecatedSince: "8.53.0",
22
- availableUntil: "10.0.0",
23
- replacedBy: [
24
- {
25
- message: "ESLint Stylistic now maintains deprecated stylistic core rules.",
26
- url: "https://eslint.style/guide/migration",
27
- plugin: {
28
- name: "@stylistic/eslint-plugin-js",
29
- url: "https://eslint.style/packages/js"
30
- },
31
- rule: {
32
- name: "no-extra-parens",
33
- url: "https://eslint.style/rules/js/no-extra-parens"
34
- }
35
- }
36
- ]
37
- },
38
- type: "layout",
39
-
40
- docs: {
41
- description: "Disallow unnecessary parentheses",
42
- recommended: false,
43
- url: "https://eslint.org/docs/latest/rules/no-extra-parens"
44
- },
45
-
46
- fixable: "code",
47
-
48
- schema: {
49
- anyOf: [
50
- {
51
- type: "array",
52
- items: [
53
- {
54
- enum: ["functions"]
55
- }
56
- ],
57
- minItems: 0,
58
- maxItems: 1
59
- },
60
- {
61
- type: "array",
62
- items: [
63
- {
64
- enum: ["all"]
65
- },
66
- {
67
- type: "object",
68
- properties: {
69
- conditionalAssign: { type: "boolean" },
70
- ternaryOperandBinaryExpressions: { type: "boolean" },
71
- nestedBinaryExpressions: { type: "boolean" },
72
- returnAssign: { type: "boolean" },
73
- ignoreJSX: { enum: ["none", "all", "single-line", "multi-line"] },
74
- enforceForArrowConditionals: { type: "boolean" },
75
- enforceForSequenceExpressions: { type: "boolean" },
76
- enforceForNewInMemberExpressions: { type: "boolean" },
77
- enforceForFunctionPrototypeMethods: { type: "boolean" },
78
- allowParensAfterCommentPattern: { type: "string" }
79
- },
80
- additionalProperties: false
81
- }
82
- ],
83
- minItems: 0,
84
- maxItems: 2
85
- }
86
- ]
87
- },
88
-
89
- messages: {
90
- unexpected: "Unnecessary parentheses around expression."
91
- }
92
- },
93
-
94
- create(context) {
95
- const sourceCode = context.sourceCode;
96
-
97
- const tokensToIgnore = new WeakSet();
98
- const precedence = astUtils.getPrecedence;
99
- const ALL_NODES = context.options[0] !== "functions";
100
- const EXCEPT_COND_ASSIGN = ALL_NODES && context.options[1] && context.options[1].conditionalAssign === false;
101
- const EXCEPT_COND_TERNARY = ALL_NODES && context.options[1] && context.options[1].ternaryOperandBinaryExpressions === false;
102
- const NESTED_BINARY = ALL_NODES && context.options[1] && context.options[1].nestedBinaryExpressions === false;
103
- const EXCEPT_RETURN_ASSIGN = ALL_NODES && context.options[1] && context.options[1].returnAssign === false;
104
- const IGNORE_JSX = ALL_NODES && context.options[1] && context.options[1].ignoreJSX;
105
- const IGNORE_ARROW_CONDITIONALS = ALL_NODES && context.options[1] &&
106
- context.options[1].enforceForArrowConditionals === false;
107
- const IGNORE_SEQUENCE_EXPRESSIONS = ALL_NODES && context.options[1] &&
108
- context.options[1].enforceForSequenceExpressions === false;
109
- const IGNORE_NEW_IN_MEMBER_EXPR = ALL_NODES && context.options[1] &&
110
- context.options[1].enforceForNewInMemberExpressions === false;
111
- const IGNORE_FUNCTION_PROTOTYPE_METHODS = ALL_NODES && context.options[1] &&
112
- context.options[1].enforceForFunctionPrototypeMethods === false;
113
- const ALLOW_PARENS_AFTER_COMMENT_PATTERN = ALL_NODES && context.options[1] && context.options[1].allowParensAfterCommentPattern;
114
-
115
- const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({ type: "AssignmentExpression" });
116
- const PRECEDENCE_OF_UPDATE_EXPR = precedence({ type: "UpdateExpression" });
117
-
118
- let reportsBuffer;
119
-
120
- /**
121
- * Determines whether the given node is a `call` or `apply` method call, invoked directly on a `FunctionExpression` node.
122
- * Example: function(){}.call()
123
- * @param {ASTNode} node The node to be checked.
124
- * @returns {boolean} True if the node is an immediate `call` or `apply` method call.
125
- * @private
126
- */
127
- function isImmediateFunctionPrototypeMethodCall(node) {
128
- const callNode = astUtils.skipChainExpression(node);
129
-
130
- if (callNode.type !== "CallExpression") {
131
- return false;
132
- }
133
- const callee = astUtils.skipChainExpression(callNode.callee);
134
-
135
- return (
136
- callee.type === "MemberExpression" &&
137
- callee.object.type === "FunctionExpression" &&
138
- ["call", "apply"].includes(astUtils.getStaticPropertyName(callee))
139
- );
140
- }
141
-
142
- /**
143
- * Determines if this rule should be enforced for a node given the current configuration.
144
- * @param {ASTNode} node The node to be checked.
145
- * @returns {boolean} True if the rule should be enforced for this node.
146
- * @private
147
- */
148
- function ruleApplies(node) {
149
- if (node.type === "JSXElement" || node.type === "JSXFragment") {
150
- const isSingleLine = node.loc.start.line === node.loc.end.line;
151
-
152
- switch (IGNORE_JSX) {
153
-
154
- // Exclude this JSX element from linting
155
- case "all":
156
- return false;
157
-
158
- // Exclude this JSX element if it is multi-line element
159
- case "multi-line":
160
- return isSingleLine;
161
-
162
- // Exclude this JSX element if it is single-line element
163
- case "single-line":
164
- return !isSingleLine;
165
-
166
- // Nothing special to be done for JSX elements
167
- case "none":
168
- break;
169
-
170
- // no default
171
- }
172
- }
173
-
174
- if (node.type === "SequenceExpression" && IGNORE_SEQUENCE_EXPRESSIONS) {
175
- return false;
176
- }
177
-
178
- if (isImmediateFunctionPrototypeMethodCall(node) && IGNORE_FUNCTION_PROTOTYPE_METHODS) {
179
- return false;
180
- }
181
-
182
- return ALL_NODES || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
183
- }
184
-
185
- /**
186
- * Determines if a node is surrounded by parentheses.
187
- * @param {ASTNode} node The node to be checked.
188
- * @returns {boolean} True if the node is parenthesised.
189
- * @private
190
- */
191
- function isParenthesised(node) {
192
- return isParenthesizedRaw(1, node, sourceCode);
193
- }
194
-
195
- /**
196
- * Determines if a node is surrounded by parentheses twice.
197
- * @param {ASTNode} node The node to be checked.
198
- * @returns {boolean} True if the node is doubly parenthesised.
199
- * @private
200
- */
201
- function isParenthesisedTwice(node) {
202
- return isParenthesizedRaw(2, node, sourceCode);
203
- }
204
-
205
- /**
206
- * Determines if a node is surrounded by (potentially) invalid parentheses.
207
- * @param {ASTNode} node The node to be checked.
208
- * @returns {boolean} True if the node is incorrectly parenthesised.
209
- * @private
210
- */
211
- function hasExcessParens(node) {
212
- return ruleApplies(node) && isParenthesised(node);
213
- }
214
-
215
- /**
216
- * Determines if a node that is expected to be parenthesised is surrounded by
217
- * (potentially) invalid extra parentheses.
218
- * @param {ASTNode} node The node to be checked.
219
- * @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
220
- * @private
221
- */
222
- function hasDoubleExcessParens(node) {
223
- return ruleApplies(node) && isParenthesisedTwice(node);
224
- }
225
-
226
- /**
227
- * Determines if a node that is expected to be parenthesised is surrounded by
228
- * (potentially) invalid extra parentheses with considering precedence level of the node.
229
- * If the preference level of the node is not higher or equal to precedence lower limit, it also checks
230
- * whether the node is surrounded by parentheses twice or not.
231
- * @param {ASTNode} node The node to be checked.
232
- * @param {number} precedenceLowerLimit The lower limit of precedence.
233
- * @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
234
- * @private
235
- */
236
- function hasExcessParensWithPrecedence(node, precedenceLowerLimit) {
237
- if (ruleApplies(node) && isParenthesised(node)) {
238
- if (
239
- precedence(node) >= precedenceLowerLimit ||
240
- isParenthesisedTwice(node)
241
- ) {
242
- return true;
243
- }
244
- }
245
- return false;
246
- }
247
-
248
- /**
249
- * Determines if a node test expression is allowed to have a parenthesised assignment
250
- * @param {ASTNode} node The node to be checked.
251
- * @returns {boolean} True if the assignment can be parenthesised.
252
- * @private
253
- */
254
- function isCondAssignException(node) {
255
- return EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression";
256
- }
257
-
258
- /**
259
- * Determines if a node is in a return statement
260
- * @param {ASTNode} node The node to be checked.
261
- * @returns {boolean} True if the node is in a return statement.
262
- * @private
263
- */
264
- function isInReturnStatement(node) {
265
- for (let currentNode = node; currentNode; currentNode = currentNode.parent) {
266
- if (
267
- currentNode.type === "ReturnStatement" ||
268
- (currentNode.type === "ArrowFunctionExpression" && currentNode.body.type !== "BlockStatement")
269
- ) {
270
- return true;
271
- }
272
- }
273
-
274
- return false;
275
- }
276
-
277
- /**
278
- * Determines if a constructor function is newed-up with parens
279
- * @param {ASTNode} newExpression The NewExpression node to be checked.
280
- * @returns {boolean} True if the constructor is called with parens.
281
- * @private
282
- */
283
- function isNewExpressionWithParens(newExpression) {
284
- const lastToken = sourceCode.getLastToken(newExpression);
285
- const penultimateToken = sourceCode.getTokenBefore(lastToken);
286
-
287
- return newExpression.arguments.length > 0 ||
288
- (
289
-
290
- // The expression should end with its own parens, e.g., new new foo() is not a new expression with parens
291
- astUtils.isOpeningParenToken(penultimateToken) &&
292
- astUtils.isClosingParenToken(lastToken) &&
293
- newExpression.callee.range[1] < newExpression.range[1]
294
- );
295
- }
296
-
297
- /**
298
- * Determines if a node is or contains an assignment expression
299
- * @param {ASTNode} node The node to be checked.
300
- * @returns {boolean} True if the node is or contains an assignment expression.
301
- * @private
302
- */
303
- function containsAssignment(node) {
304
- if (node.type === "AssignmentExpression") {
305
- return true;
306
- }
307
- if (node.type === "ConditionalExpression" &&
308
- (node.consequent.type === "AssignmentExpression" || node.alternate.type === "AssignmentExpression")) {
309
- return true;
310
- }
311
- if ((node.left && node.left.type === "AssignmentExpression") ||
312
- (node.right && node.right.type === "AssignmentExpression")) {
313
- return true;
314
- }
315
-
316
- return false;
317
- }
318
-
319
- /**
320
- * Determines if a node is contained by or is itself a return statement and is allowed to have a parenthesised assignment
321
- * @param {ASTNode} node The node to be checked.
322
- * @returns {boolean} True if the assignment can be parenthesised.
323
- * @private
324
- */
325
- function isReturnAssignException(node) {
326
- if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) {
327
- return false;
328
- }
329
-
330
- if (node.type === "ReturnStatement") {
331
- return node.argument && containsAssignment(node.argument);
332
- }
333
- if (node.type === "ArrowFunctionExpression" && node.body.type !== "BlockStatement") {
334
- return containsAssignment(node.body);
335
- }
336
- return containsAssignment(node);
337
-
338
- }
339
-
340
- /**
341
- * Determines if a node following a [no LineTerminator here] restriction is
342
- * surrounded by (potentially) invalid extra parentheses.
343
- * @param {Token} token The token preceding the [no LineTerminator here] restriction.
344
- * @param {ASTNode} node The node to be checked.
345
- * @returns {boolean} True if the node is incorrectly parenthesised.
346
- * @private
347
- */
348
- function hasExcessParensNoLineTerminator(token, node) {
349
- if (token.loc.end.line === node.loc.start.line) {
350
- return hasExcessParens(node);
351
- }
352
-
353
- return hasDoubleExcessParens(node);
354
- }
355
-
356
- /**
357
- * Determines whether a node should be preceded by an additional space when removing parens
358
- * @param {ASTNode} node node to evaluate; must be surrounded by parentheses
359
- * @returns {boolean} `true` if a space should be inserted before the node
360
- * @private
361
- */
362
- function requiresLeadingSpace(node) {
363
- const leftParenToken = sourceCode.getTokenBefore(node);
364
- const tokenBeforeLeftParen = sourceCode.getTokenBefore(leftParenToken, { includeComments: true });
365
- const tokenAfterLeftParen = sourceCode.getTokenAfter(leftParenToken, { includeComments: true });
366
-
367
- return tokenBeforeLeftParen &&
368
- tokenBeforeLeftParen.range[1] === leftParenToken.range[0] &&
369
- leftParenToken.range[1] === tokenAfterLeftParen.range[0] &&
370
- !astUtils.canTokensBeAdjacent(tokenBeforeLeftParen, tokenAfterLeftParen);
371
- }
372
-
373
- /**
374
- * Determines whether a node should be followed by an additional space when removing parens
375
- * @param {ASTNode} node node to evaluate; must be surrounded by parentheses
376
- * @returns {boolean} `true` if a space should be inserted after the node
377
- * @private
378
- */
379
- function requiresTrailingSpace(node) {
380
- const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 });
381
- const rightParenToken = nextTwoTokens[0];
382
- const tokenAfterRightParen = nextTwoTokens[1];
383
- const tokenBeforeRightParen = sourceCode.getLastToken(node);
384
-
385
- return rightParenToken && tokenAfterRightParen &&
386
- !sourceCode.isSpaceBetweenTokens(rightParenToken, tokenAfterRightParen) &&
387
- !astUtils.canTokensBeAdjacent(tokenBeforeRightParen, tokenAfterRightParen);
388
- }
389
-
390
- /**
391
- * Determines if a given expression node is an IIFE
392
- * @param {ASTNode} node The node to check
393
- * @returns {boolean} `true` if the given node is an IIFE
394
- */
395
- function isIIFE(node) {
396
- const maybeCallNode = astUtils.skipChainExpression(node);
397
-
398
- return maybeCallNode.type === "CallExpression" && maybeCallNode.callee.type === "FunctionExpression";
399
- }
400
-
401
- /**
402
- * Determines if the given node can be the assignment target in destructuring or the LHS of an assignment.
403
- * This is to avoid an autofix that could change behavior because parsers mistakenly allow invalid syntax,
404
- * such as `(a = b) = c` and `[(a = b) = c] = []`. Ideally, this function shouldn't be necessary.
405
- * @param {ASTNode} [node] The node to check
406
- * @returns {boolean} `true` if the given node can be a valid assignment target
407
- */
408
- function canBeAssignmentTarget(node) {
409
- return node && (node.type === "Identifier" || node.type === "MemberExpression");
410
- }
411
-
412
- /**
413
- * Checks if a node is fixable.
414
- * A node is fixable if removing a single pair of surrounding parentheses does not turn it
415
- * into a directive after fixing other nodes.
416
- * Almost all nodes are fixable, except if all of the following conditions are met:
417
- * The node is a string Literal
418
- * It has a single pair of parentheses
419
- * It is the only child of an ExpressionStatement
420
- * @param {ASTNode} node The node to evaluate.
421
- * @returns {boolean} Whether or not the node is fixable.
422
- * @private
423
- */
424
- function isFixable(node) {
425
-
426
- // if it's not a string literal it can be autofixed
427
- if (node.type !== "Literal" || typeof node.value !== "string") {
428
- return true;
429
- }
430
- if (isParenthesisedTwice(node)) {
431
- return true;
432
- }
433
- return !astUtils.isTopLevelExpressionStatement(node.parent);
434
- }
435
-
436
- /**
437
- * Report the node
438
- * @param {ASTNode} node node to evaluate
439
- * @returns {void}
440
- * @private
441
- */
442
- function report(node) {
443
- const leftParenToken = sourceCode.getTokenBefore(node);
444
- const rightParenToken = sourceCode.getTokenAfter(node);
445
-
446
- if (!isParenthesisedTwice(node)) {
447
- if (tokensToIgnore.has(sourceCode.getFirstToken(node))) {
448
- return;
449
- }
450
-
451
- if (isIIFE(node) && !isParenthesised(node.callee)) {
452
- return;
453
- }
454
-
455
- if (ALLOW_PARENS_AFTER_COMMENT_PATTERN) {
456
- const commentsBeforeLeftParenToken = sourceCode.getCommentsBefore(leftParenToken);
457
- const totalCommentsBeforeLeftParenTokenCount = commentsBeforeLeftParenToken.length;
458
- const ignorePattern = new RegExp(ALLOW_PARENS_AFTER_COMMENT_PATTERN, "u");
459
-
460
- if (
461
- totalCommentsBeforeLeftParenTokenCount > 0 &&
462
- ignorePattern.test(commentsBeforeLeftParenToken[totalCommentsBeforeLeftParenTokenCount - 1].value)
463
- ) {
464
- return;
465
- }
466
- }
467
- }
468
-
469
- /**
470
- * Finishes reporting
471
- * @returns {void}
472
- * @private
473
- */
474
- function finishReport() {
475
- context.report({
476
- node,
477
- loc: leftParenToken.loc,
478
- messageId: "unexpected",
479
- fix: isFixable(node)
480
- ? fixer => {
481
- const parenthesizedSource = sourceCode.text.slice(leftParenToken.range[1], rightParenToken.range[0]);
482
-
483
- return fixer.replaceTextRange([
484
- leftParenToken.range[0],
485
- rightParenToken.range[1]
486
- ], (requiresLeadingSpace(node) ? " " : "") + parenthesizedSource + (requiresTrailingSpace(node) ? " " : ""));
487
- }
488
- : null
489
- });
490
- }
491
-
492
- if (reportsBuffer) {
493
- reportsBuffer.reports.push({ node, finishReport });
494
- return;
495
- }
496
-
497
- finishReport();
498
- }
499
-
500
- /**
501
- * Evaluate a argument of the node.
502
- * @param {ASTNode} node node to evaluate
503
- * @returns {void}
504
- * @private
505
- */
506
- function checkArgumentWithPrecedence(node) {
507
- if (hasExcessParensWithPrecedence(node.argument, precedence(node))) {
508
- report(node.argument);
509
- }
510
- }
511
-
512
- /**
513
- * Check if a member expression contains a call expression
514
- * @param {ASTNode} node MemberExpression node to evaluate
515
- * @returns {boolean} true if found, false if not
516
- */
517
- function doesMemberExpressionContainCallExpression(node) {
518
- let currentNode = node.object;
519
- let currentNodeType = node.object.type;
520
-
521
- while (currentNodeType === "MemberExpression") {
522
- currentNode = currentNode.object;
523
- currentNodeType = currentNode.type;
524
- }
525
-
526
- return currentNodeType === "CallExpression";
527
- }
528
-
529
- /**
530
- * Evaluate a new call
531
- * @param {ASTNode} node node to evaluate
532
- * @returns {void}
533
- * @private
534
- */
535
- function checkCallNew(node) {
536
- const callee = node.callee;
537
-
538
- if (hasExcessParensWithPrecedence(callee, precedence(node))) {
539
- if (
540
- hasDoubleExcessParens(callee) ||
541
- !(
542
- isIIFE(node) ||
543
-
544
- // (new A)(); new (new A)();
545
- (
546
- callee.type === "NewExpression" &&
547
- !isNewExpressionWithParens(callee) &&
548
- !(
549
- node.type === "NewExpression" &&
550
- !isNewExpressionWithParens(node)
551
- )
552
- ) ||
553
-
554
- // new (a().b)(); new (a.b().c);
555
- (
556
- node.type === "NewExpression" &&
557
- callee.type === "MemberExpression" &&
558
- doesMemberExpressionContainCallExpression(callee)
559
- ) ||
560
-
561
- // (a?.b)(); (a?.())();
562
- (
563
- !node.optional &&
564
- callee.type === "ChainExpression"
565
- )
566
- )
567
- ) {
568
- report(node.callee);
569
- }
570
- }
571
- node.arguments
572
- .filter(arg => hasExcessParensWithPrecedence(arg, PRECEDENCE_OF_ASSIGNMENT_EXPR))
573
- .forEach(report);
574
- }
575
-
576
- /**
577
- * Evaluate binary logicals
578
- * @param {ASTNode} node node to evaluate
579
- * @returns {void}
580
- * @private
581
- */
582
- function checkBinaryLogical(node) {
583
- const prec = precedence(node);
584
- const leftPrecedence = precedence(node.left);
585
- const rightPrecedence = precedence(node.right);
586
- const isExponentiation = node.operator === "**";
587
- const shouldSkipLeft = NESTED_BINARY && (node.left.type === "BinaryExpression" || node.left.type === "LogicalExpression");
588
- const shouldSkipRight = NESTED_BINARY && (node.right.type === "BinaryExpression" || node.right.type === "LogicalExpression");
589
-
590
- if (!shouldSkipLeft && hasExcessParens(node.left)) {
591
- if (
592
- !(["AwaitExpression", "UnaryExpression"].includes(node.left.type) && isExponentiation) &&
593
- !astUtils.isMixedLogicalAndCoalesceExpressions(node.left, node) &&
594
- (leftPrecedence > prec || (leftPrecedence === prec && !isExponentiation)) ||
595
- isParenthesisedTwice(node.left)
596
- ) {
597
- report(node.left);
598
- }
599
- }
600
-
601
- if (!shouldSkipRight && hasExcessParens(node.right)) {
602
- if (
603
- !astUtils.isMixedLogicalAndCoalesceExpressions(node.right, node) &&
604
- (rightPrecedence > prec || (rightPrecedence === prec && isExponentiation)) ||
605
- isParenthesisedTwice(node.right)
606
- ) {
607
- report(node.right);
608
- }
609
- }
610
- }
611
-
612
- /**
613
- * Check the parentheses around the super class of the given class definition.
614
- * @param {ASTNode} node The node of class declarations to check.
615
- * @returns {void}
616
- */
617
- function checkClass(node) {
618
- if (!node.superClass) {
619
- return;
620
- }
621
-
622
- /*
623
- * If `node.superClass` is a LeftHandSideExpression, parentheses are extra.
624
- * Otherwise, parentheses are needed.
625
- */
626
- const hasExtraParens = precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR
627
- ? hasExcessParens(node.superClass)
628
- : hasDoubleExcessParens(node.superClass);
629
-
630
- if (hasExtraParens) {
631
- report(node.superClass);
632
- }
633
- }
634
-
635
- /**
636
- * Check the parentheses around the argument of the given spread operator.
637
- * @param {ASTNode} node The node of spread elements/properties to check.
638
- * @returns {void}
639
- */
640
- function checkSpreadOperator(node) {
641
- if (hasExcessParensWithPrecedence(node.argument, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
642
- report(node.argument);
643
- }
644
- }
645
-
646
- /**
647
- * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration
648
- * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node
649
- * @returns {void}
650
- */
651
- function checkExpressionOrExportStatement(node) {
652
- const firstToken = isParenthesised(node) ? sourceCode.getTokenBefore(node) : sourceCode.getFirstToken(node);
653
- const secondToken = sourceCode.getTokenAfter(firstToken, astUtils.isNotOpeningParenToken);
654
- const thirdToken = secondToken ? sourceCode.getTokenAfter(secondToken) : null;
655
- const tokenAfterClosingParens = secondToken ? sourceCode.getTokenAfter(secondToken, astUtils.isNotClosingParenToken) : null;
656
-
657
- if (
658
- astUtils.isOpeningParenToken(firstToken) &&
659
- (
660
- astUtils.isOpeningBraceToken(secondToken) ||
661
- secondToken.type === "Keyword" && (
662
- secondToken.value === "function" ||
663
- secondToken.value === "class" ||
664
- secondToken.value === "let" &&
665
- tokenAfterClosingParens &&
666
- (
667
- astUtils.isOpeningBracketToken(tokenAfterClosingParens) ||
668
- tokenAfterClosingParens.type === "Identifier"
669
- )
670
- ) ||
671
- secondToken && secondToken.type === "Identifier" && secondToken.value === "async" && thirdToken && thirdToken.type === "Keyword" && thirdToken.value === "function"
672
- )
673
- ) {
674
- tokensToIgnore.add(secondToken);
675
- }
676
-
677
- const hasExtraParens = node.parent.type === "ExportDefaultDeclaration"
678
- ? hasExcessParensWithPrecedence(node, PRECEDENCE_OF_ASSIGNMENT_EXPR)
679
- : hasExcessParens(node);
680
-
681
- if (hasExtraParens) {
682
- report(node);
683
- }
684
- }
685
-
686
- /**
687
- * Finds the path from the given node to the specified ancestor.
688
- * @param {ASTNode} node First node in the path.
689
- * @param {ASTNode} ancestor Last node in the path.
690
- * @returns {ASTNode[]} Path, including both nodes.
691
- * @throws {Error} If the given node does not have the specified ancestor.
692
- */
693
- function pathToAncestor(node, ancestor) {
694
- const path = [node];
695
- let currentNode = node;
696
-
697
- while (currentNode !== ancestor) {
698
-
699
- currentNode = currentNode.parent;
700
-
701
- /* c8 ignore start */
702
- if (currentNode === null) {
703
- throw new Error("Nodes are not in the ancestor-descendant relationship.");
704
- }/* c8 ignore stop */
705
-
706
- path.push(currentNode);
707
- }
708
-
709
- return path;
710
- }
711
-
712
- /**
713
- * Finds the path from the given node to the specified descendant.
714
- * @param {ASTNode} node First node in the path.
715
- * @param {ASTNode} descendant Last node in the path.
716
- * @returns {ASTNode[]} Path, including both nodes.
717
- * @throws {Error} If the given node does not have the specified descendant.
718
- */
719
- function pathToDescendant(node, descendant) {
720
- return pathToAncestor(descendant, node).reverse();
721
- }
722
-
723
- /**
724
- * Checks whether the syntax of the given ancestor of an 'in' expression inside a for-loop initializer
725
- * is preventing the 'in' keyword from being interpreted as a part of an ill-formed for-in loop.
726
- * @param {ASTNode} node Ancestor of an 'in' expression.
727
- * @param {ASTNode} child Child of the node, ancestor of the same 'in' expression or the 'in' expression itself.
728
- * @returns {boolean} True if the keyword 'in' would be interpreted as the 'in' operator, without any parenthesis.
729
- */
730
- function isSafelyEnclosingInExpression(node, child) {
731
- switch (node.type) {
732
- case "ArrayExpression":
733
- case "ArrayPattern":
734
- case "BlockStatement":
735
- case "ObjectExpression":
736
- case "ObjectPattern":
737
- case "TemplateLiteral":
738
- return true;
739
- case "ArrowFunctionExpression":
740
- case "FunctionExpression":
741
- return node.params.includes(child);
742
- case "CallExpression":
743
- case "NewExpression":
744
- return node.arguments.includes(child);
745
- case "MemberExpression":
746
- return node.computed && node.property === child;
747
- case "ConditionalExpression":
748
- return node.consequent === child;
749
- default:
750
- return false;
751
- }
752
- }
753
-
754
- /**
755
- * Starts a new reports buffering. Warnings will be stored in a buffer instead of being reported immediately.
756
- * An additional logic that requires multiple nodes (e.g. a whole subtree) may dismiss some of the stored warnings.
757
- * @returns {void}
758
- */
759
- function startNewReportsBuffering() {
760
- reportsBuffer = {
761
- upper: reportsBuffer,
762
- inExpressionNodes: [],
763
- reports: []
764
- };
765
- }
766
-
767
- /**
768
- * Ends the current reports buffering.
769
- * @returns {void}
770
- */
771
- function endCurrentReportsBuffering() {
772
- const { upper, inExpressionNodes, reports } = reportsBuffer;
773
-
774
- if (upper) {
775
- upper.inExpressionNodes.push(...inExpressionNodes);
776
- upper.reports.push(...reports);
777
- } else {
778
-
779
- // flush remaining reports
780
- reports.forEach(({ finishReport }) => finishReport());
781
- }
782
-
783
- reportsBuffer = upper;
784
- }
785
-
786
- /**
787
- * Checks whether the given node is in the current reports buffer.
788
- * @param {ASTNode} node Node to check.
789
- * @returns {boolean} True if the node is in the current buffer, false otherwise.
790
- */
791
- function isInCurrentReportsBuffer(node) {
792
- return reportsBuffer.reports.some(r => r.node === node);
793
- }
794
-
795
- /**
796
- * Removes the given node from the current reports buffer.
797
- * @param {ASTNode} node Node to remove.
798
- * @returns {void}
799
- */
800
- function removeFromCurrentReportsBuffer(node) {
801
- reportsBuffer.reports = reportsBuffer.reports.filter(r => r.node !== node);
802
- }
803
-
804
- /**
805
- * Checks whether a node is a MemberExpression at NewExpression's callee.
806
- * @param {ASTNode} node node to check.
807
- * @returns {boolean} True if the node is a MemberExpression at NewExpression's callee. false otherwise.
808
- */
809
- function isMemberExpInNewCallee(node) {
810
- if (node.type === "MemberExpression") {
811
- return node.parent.type === "NewExpression" && node.parent.callee === node
812
- ? true
813
- : node.parent.object === node && isMemberExpInNewCallee(node.parent);
814
- }
815
- return false;
816
- }
817
-
818
- /**
819
- * Checks if the left-hand side of an assignment is an identifier, the operator is one of
820
- * `=`, `&&=`, `||=` or `??=` and the right-hand side is an anonymous class or function.
821
- *
822
- * As per https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation, an
823
- * assignment involving one of the operators `=`, `&&=`, `||=` or `??=` where the right-hand
824
- * side is an anonymous class or function and the left-hand side is an *unparenthesized*
825
- * identifier has different semantics than other assignments.
826
- * Specifically, when an expression like `foo = function () {}` is evaluated, `foo.name`
827
- * will be set to the string "foo", i.e. the identifier name. The same thing does not happen
828
- * when evaluating `(foo) = function () {}`.
829
- * Since the parenthesizing of the identifier in the left-hand side is significant in this
830
- * special case, the parentheses, if present, should not be flagged as unnecessary.
831
- * @param {ASTNode} node an AssignmentExpression node.
832
- * @returns {boolean} `true` if the left-hand side of the assignment is an identifier, the
833
- * operator is one of `=`, `&&=`, `||=` or `??=` and the right-hand side is an anonymous
834
- * class or function; otherwise, `false`.
835
- */
836
- function isAnonymousFunctionAssignmentException({ left, operator, right }) {
837
- if (left.type === "Identifier" && ["=", "&&=", "||=", "??="].includes(operator)) {
838
- const rhsType = right.type;
839
-
840
- if (rhsType === "ArrowFunctionExpression") {
841
- return true;
842
- }
843
- if ((rhsType === "FunctionExpression" || rhsType === "ClassExpression") && !right.id) {
844
- return true;
845
- }
846
- }
847
- return false;
848
- }
849
-
850
- return {
851
- ArrayExpression(node) {
852
- node.elements
853
- .filter(e => e && hasExcessParensWithPrecedence(e, PRECEDENCE_OF_ASSIGNMENT_EXPR))
854
- .forEach(report);
855
- },
856
-
857
- ArrayPattern(node) {
858
- node.elements
859
- .filter(e => canBeAssignmentTarget(e) && hasExcessParens(e))
860
- .forEach(report);
861
- },
862
-
863
- ArrowFunctionExpression(node) {
864
- if (isReturnAssignException(node)) {
865
- return;
866
- }
867
-
868
- if (node.body.type === "ConditionalExpression" &&
869
- IGNORE_ARROW_CONDITIONALS
870
- ) {
871
- return;
872
- }
873
-
874
- if (node.body.type !== "BlockStatement") {
875
- const firstBodyToken = sourceCode.getFirstToken(node.body, astUtils.isNotOpeningParenToken);
876
- const tokenBeforeFirst = sourceCode.getTokenBefore(firstBodyToken);
877
-
878
- if (astUtils.isOpeningParenToken(tokenBeforeFirst) && astUtils.isOpeningBraceToken(firstBodyToken)) {
879
- tokensToIgnore.add(firstBodyToken);
880
- }
881
- if (hasExcessParensWithPrecedence(node.body, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
882
- report(node.body);
883
- }
884
- }
885
- },
886
-
887
- AssignmentExpression(node) {
888
- if (canBeAssignmentTarget(node.left) && hasExcessParens(node.left) &&
889
- (!isAnonymousFunctionAssignmentException(node) || isParenthesisedTwice(node.left))) {
890
- report(node.left);
891
- }
892
-
893
- if (!isReturnAssignException(node) && hasExcessParensWithPrecedence(node.right, precedence(node))) {
894
- report(node.right);
895
- }
896
- },
897
-
898
- BinaryExpression(node) {
899
- if (reportsBuffer && node.operator === "in") {
900
- reportsBuffer.inExpressionNodes.push(node);
901
- }
902
-
903
- checkBinaryLogical(node);
904
- },
905
-
906
- CallExpression: checkCallNew,
907
-
908
- ConditionalExpression(node) {
909
- if (isReturnAssignException(node)) {
910
- return;
911
- }
912
-
913
- const availableTypes = new Set(["BinaryExpression", "LogicalExpression"]);
914
-
915
- if (
916
- !(EXCEPT_COND_TERNARY && availableTypes.has(node.test.type)) &&
917
- !isCondAssignException(node) &&
918
- hasExcessParensWithPrecedence(node.test, precedence({ type: "LogicalExpression", operator: "||" }))
919
- ) {
920
- report(node.test);
921
- }
922
-
923
- if (
924
- !(EXCEPT_COND_TERNARY && availableTypes.has(node.consequent.type)) &&
925
- hasExcessParensWithPrecedence(node.consequent, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
926
- report(node.consequent);
927
- }
928
-
929
- if (
930
- !(EXCEPT_COND_TERNARY && availableTypes.has(node.alternate.type)) &&
931
- hasExcessParensWithPrecedence(node.alternate, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
932
- report(node.alternate);
933
- }
934
- },
935
-
936
- DoWhileStatement(node) {
937
- if (hasExcessParens(node.test) && !isCondAssignException(node)) {
938
- report(node.test);
939
- }
940
- },
941
-
942
- ExportDefaultDeclaration: node => checkExpressionOrExportStatement(node.declaration),
943
- ExpressionStatement: node => checkExpressionOrExportStatement(node.expression),
944
-
945
- ForInStatement(node) {
946
- if (node.left.type !== "VariableDeclaration") {
947
- const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken);
948
-
949
- if (
950
- firstLeftToken.value === "let" &&
951
- astUtils.isOpeningBracketToken(
952
- sourceCode.getTokenAfter(firstLeftToken, astUtils.isNotClosingParenToken)
953
- )
954
- ) {
955
-
956
- // ForInStatement#left expression cannot start with `let[`.
957
- tokensToIgnore.add(firstLeftToken);
958
- }
959
- }
960
-
961
- if (hasExcessParens(node.left)) {
962
- report(node.left);
963
- }
964
-
965
- if (hasExcessParens(node.right)) {
966
- report(node.right);
967
- }
968
- },
969
-
970
- ForOfStatement(node) {
971
- if (node.left.type !== "VariableDeclaration") {
972
- const firstLeftToken = sourceCode.getFirstToken(node.left, astUtils.isNotOpeningParenToken);
973
-
974
- if (firstLeftToken.value === "let") {
975
-
976
- // ForOfStatement#left expression cannot start with `let`.
977
- tokensToIgnore.add(firstLeftToken);
978
- }
979
- }
980
-
981
- if (hasExcessParens(node.left)) {
982
- report(node.left);
983
- }
984
-
985
- if (hasExcessParensWithPrecedence(node.right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
986
- report(node.right);
987
- }
988
- },
989
-
990
- ForStatement(node) {
991
- if (node.test && hasExcessParens(node.test) && !isCondAssignException(node)) {
992
- report(node.test);
993
- }
994
-
995
- if (node.update && hasExcessParens(node.update)) {
996
- report(node.update);
997
- }
998
-
999
- if (node.init) {
1000
-
1001
- if (node.init.type !== "VariableDeclaration") {
1002
- const firstToken = sourceCode.getFirstToken(node.init, astUtils.isNotOpeningParenToken);
1003
-
1004
- if (
1005
- firstToken.value === "let" &&
1006
- astUtils.isOpeningBracketToken(
1007
- sourceCode.getTokenAfter(firstToken, astUtils.isNotClosingParenToken)
1008
- )
1009
- ) {
1010
-
1011
- // ForStatement#init expression cannot start with `let[`.
1012
- tokensToIgnore.add(firstToken);
1013
- }
1014
- }
1015
-
1016
- startNewReportsBuffering();
1017
-
1018
- if (hasExcessParens(node.init)) {
1019
- report(node.init);
1020
- }
1021
- }
1022
- },
1023
-
1024
- "ForStatement > *.init:exit"(node) {
1025
-
1026
- /*
1027
- * Removing parentheses around `in` expressions might change semantics and cause errors.
1028
- *
1029
- * For example, this valid for loop:
1030
- * for (let a = (b in c); ;);
1031
- * after removing parentheses would be treated as an invalid for-in loop:
1032
- * for (let a = b in c; ;);
1033
- */
1034
-
1035
- if (reportsBuffer.reports.length) {
1036
- reportsBuffer.inExpressionNodes.forEach(inExpressionNode => {
1037
- const path = pathToDescendant(node, inExpressionNode);
1038
- let nodeToExclude;
1039
-
1040
- for (let i = 0; i < path.length; i++) {
1041
- const pathNode = path[i];
1042
-
1043
- if (i < path.length - 1) {
1044
- const nextPathNode = path[i + 1];
1045
-
1046
- if (isSafelyEnclosingInExpression(pathNode, nextPathNode)) {
1047
-
1048
- // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]').
1049
- return;
1050
- }
1051
- }
1052
-
1053
- if (isParenthesised(pathNode)) {
1054
- if (isInCurrentReportsBuffer(pathNode)) {
1055
-
1056
- // This node was supposed to be reported, but parentheses might be necessary.
1057
-
1058
- if (isParenthesisedTwice(pathNode)) {
1059
-
1060
- /*
1061
- * This node is parenthesised twice, it certainly has at least one pair of `extra` parentheses.
1062
- * If the --fix option is on, the current fixing iteration will remove only one pair of parentheses.
1063
- * The remaining pair is safely enclosing the 'in' expression.
1064
- */
1065
- return;
1066
- }
1067
-
1068
- // Exclude the outermost node only.
1069
- if (!nodeToExclude) {
1070
- nodeToExclude = pathNode;
1071
- }
1072
-
1073
- // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside.
1074
-
1075
- } else {
1076
-
1077
- // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'.
1078
- return;
1079
- }
1080
- }
1081
- }
1082
-
1083
- // Exclude the node from the list (i.e. treat parentheses as necessary)
1084
- removeFromCurrentReportsBuffer(nodeToExclude);
1085
- });
1086
- }
1087
-
1088
- endCurrentReportsBuffering();
1089
- },
1090
-
1091
- IfStatement(node) {
1092
- if (hasExcessParens(node.test) && !isCondAssignException(node)) {
1093
- report(node.test);
1094
- }
1095
- },
1096
-
1097
- ImportExpression(node) {
1098
- const { source } = node;
1099
-
1100
- if (source.type === "SequenceExpression") {
1101
- if (hasDoubleExcessParens(source)) {
1102
- report(source);
1103
- }
1104
- } else if (hasExcessParens(source)) {
1105
- report(source);
1106
- }
1107
- },
1108
-
1109
- LogicalExpression: checkBinaryLogical,
1110
-
1111
- MemberExpression(node) {
1112
- const shouldAllowWrapOnce = isMemberExpInNewCallee(node) &&
1113
- doesMemberExpressionContainCallExpression(node);
1114
- const nodeObjHasExcessParens = shouldAllowWrapOnce
1115
- ? hasDoubleExcessParens(node.object)
1116
- : hasExcessParens(node.object) &&
1117
- !(
1118
- isImmediateFunctionPrototypeMethodCall(node.parent) &&
1119
- node.parent.callee === node &&
1120
- IGNORE_FUNCTION_PROTOTYPE_METHODS
1121
- );
1122
-
1123
- if (
1124
- nodeObjHasExcessParens &&
1125
- precedence(node.object) >= precedence(node) &&
1126
- (
1127
- node.computed ||
1128
- !(
1129
- astUtils.isDecimalInteger(node.object) ||
1130
-
1131
- // RegExp literal is allowed to have parens (#1589)
1132
- (node.object.type === "Literal" && node.object.regex)
1133
- )
1134
- )
1135
- ) {
1136
- report(node.object);
1137
- }
1138
-
1139
- if (nodeObjHasExcessParens &&
1140
- node.object.type === "CallExpression"
1141
- ) {
1142
- report(node.object);
1143
- }
1144
-
1145
- if (nodeObjHasExcessParens &&
1146
- !IGNORE_NEW_IN_MEMBER_EXPR &&
1147
- node.object.type === "NewExpression" &&
1148
- isNewExpressionWithParens(node.object)) {
1149
- report(node.object);
1150
- }
1151
-
1152
- if (nodeObjHasExcessParens &&
1153
- node.optional &&
1154
- node.object.type === "ChainExpression"
1155
- ) {
1156
- report(node.object);
1157
- }
1158
-
1159
- if (node.computed && hasExcessParens(node.property)) {
1160
- report(node.property);
1161
- }
1162
- },
1163
-
1164
- "MethodDefinition[computed=true]"(node) {
1165
- if (hasExcessParensWithPrecedence(node.key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
1166
- report(node.key);
1167
- }
1168
- },
1169
-
1170
- NewExpression: checkCallNew,
1171
-
1172
- ObjectExpression(node) {
1173
- node.properties
1174
- .filter(property => property.value && hasExcessParensWithPrecedence(property.value, PRECEDENCE_OF_ASSIGNMENT_EXPR))
1175
- .forEach(property => report(property.value));
1176
- },
1177
-
1178
- ObjectPattern(node) {
1179
- node.properties
1180
- .filter(property => {
1181
- const value = property.value;
1182
-
1183
- return canBeAssignmentTarget(value) && hasExcessParens(value);
1184
- }).forEach(property => report(property.value));
1185
- },
1186
-
1187
- Property(node) {
1188
- if (node.computed) {
1189
- const { key } = node;
1190
-
1191
- if (key && hasExcessParensWithPrecedence(key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
1192
- report(key);
1193
- }
1194
- }
1195
- },
1196
-
1197
- PropertyDefinition(node) {
1198
- if (node.computed && hasExcessParensWithPrecedence(node.key, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
1199
- report(node.key);
1200
- }
1201
-
1202
- if (node.value && hasExcessParensWithPrecedence(node.value, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
1203
- report(node.value);
1204
- }
1205
- },
1206
-
1207
- RestElement(node) {
1208
- const argument = node.argument;
1209
-
1210
- if (canBeAssignmentTarget(argument) && hasExcessParens(argument)) {
1211
- report(argument);
1212
- }
1213
- },
1214
-
1215
- ReturnStatement(node) {
1216
- const returnToken = sourceCode.getFirstToken(node);
1217
-
1218
- if (isReturnAssignException(node)) {
1219
- return;
1220
- }
1221
-
1222
- if (node.argument &&
1223
- hasExcessParensNoLineTerminator(returnToken, node.argument) &&
1224
-
1225
- // RegExp literal is allowed to have parens (#1589)
1226
- !(node.argument.type === "Literal" && node.argument.regex)) {
1227
- report(node.argument);
1228
- }
1229
- },
1230
-
1231
- SequenceExpression(node) {
1232
- const precedenceOfNode = precedence(node);
1233
-
1234
- node.expressions
1235
- .filter(e => hasExcessParensWithPrecedence(e, precedenceOfNode))
1236
- .forEach(report);
1237
- },
1238
-
1239
- SwitchCase(node) {
1240
- if (node.test && hasExcessParens(node.test)) {
1241
- report(node.test);
1242
- }
1243
- },
1244
-
1245
- SwitchStatement(node) {
1246
- if (hasExcessParens(node.discriminant)) {
1247
- report(node.discriminant);
1248
- }
1249
- },
1250
-
1251
- ThrowStatement(node) {
1252
- const throwToken = sourceCode.getFirstToken(node);
1253
-
1254
- if (hasExcessParensNoLineTerminator(throwToken, node.argument)) {
1255
- report(node.argument);
1256
- }
1257
- },
1258
-
1259
- UnaryExpression: checkArgumentWithPrecedence,
1260
- UpdateExpression(node) {
1261
- if (node.prefix) {
1262
- checkArgumentWithPrecedence(node);
1263
- } else {
1264
- const { argument } = node;
1265
- const operatorToken = sourceCode.getLastToken(node);
1266
-
1267
- if (argument.loc.end.line === operatorToken.loc.start.line) {
1268
- checkArgumentWithPrecedence(node);
1269
- } else {
1270
- if (hasDoubleExcessParens(argument)) {
1271
- report(argument);
1272
- }
1273
- }
1274
- }
1275
- },
1276
- AwaitExpression: checkArgumentWithPrecedence,
1277
-
1278
- VariableDeclarator(node) {
1279
- if (
1280
- node.init && hasExcessParensWithPrecedence(node.init, PRECEDENCE_OF_ASSIGNMENT_EXPR) &&
1281
-
1282
- // RegExp literal is allowed to have parens (#1589)
1283
- !(node.init.type === "Literal" && node.init.regex)
1284
- ) {
1285
- report(node.init);
1286
- }
1287
- },
1288
-
1289
- WhileStatement(node) {
1290
- if (hasExcessParens(node.test) && !isCondAssignException(node)) {
1291
- report(node.test);
1292
- }
1293
- },
1294
-
1295
- WithStatement(node) {
1296
- if (hasExcessParens(node.object)) {
1297
- report(node.object);
1298
- }
1299
- },
1300
-
1301
- YieldExpression(node) {
1302
- if (node.argument) {
1303
- const yieldToken = sourceCode.getFirstToken(node);
1304
-
1305
- if ((precedence(node.argument) >= precedence(node) &&
1306
- hasExcessParensNoLineTerminator(yieldToken, node.argument)) ||
1307
- hasDoubleExcessParens(node.argument)) {
1308
- report(node.argument);
1309
- }
1310
- }
1311
- },
1312
-
1313
- ClassDeclaration: checkClass,
1314
- ClassExpression: checkClass,
1315
-
1316
- SpreadElement: checkSpreadOperator,
1317
- SpreadProperty: checkSpreadOperator,
1318
- ExperimentalSpreadProperty: checkSpreadOperator,
1319
-
1320
- TemplateLiteral(node) {
1321
- node.expressions
1322
- .filter(e => e && hasExcessParens(e))
1323
- .forEach(report);
1324
- },
1325
-
1326
- AssignmentPattern(node) {
1327
- const { left, right } = node;
1328
-
1329
- if (canBeAssignmentTarget(left) && hasExcessParens(left)) {
1330
- report(left);
1331
- }
1332
-
1333
- if (right && hasExcessParensWithPrecedence(right, PRECEDENCE_OF_ASSIGNMENT_EXPR)) {
1334
- report(right);
1335
- }
1336
- }
1337
- };
1338
-
1339
- }
19
+ meta: {
20
+ deprecated: {
21
+ message: "Formatting rules are being moved out of ESLint core.",
22
+ url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
23
+ deprecatedSince: "8.53.0",
24
+ availableUntil: "10.0.0",
25
+ replacedBy: [
26
+ {
27
+ message:
28
+ "ESLint Stylistic now maintains deprecated stylistic core rules.",
29
+ url: "https://eslint.style/guide/migration",
30
+ plugin: {
31
+ name: "@stylistic/eslint-plugin-js",
32
+ url: "https://eslint.style/packages/js",
33
+ },
34
+ rule: {
35
+ name: "no-extra-parens",
36
+ url: "https://eslint.style/rules/js/no-extra-parens",
37
+ },
38
+ },
39
+ ],
40
+ },
41
+ type: "layout",
42
+
43
+ docs: {
44
+ description: "Disallow unnecessary parentheses",
45
+ recommended: false,
46
+ url: "https://eslint.org/docs/latest/rules/no-extra-parens",
47
+ },
48
+
49
+ fixable: "code",
50
+
51
+ schema: {
52
+ anyOf: [
53
+ {
54
+ type: "array",
55
+ items: [
56
+ {
57
+ enum: ["functions"],
58
+ },
59
+ ],
60
+ minItems: 0,
61
+ maxItems: 1,
62
+ },
63
+ {
64
+ type: "array",
65
+ items: [
66
+ {
67
+ enum: ["all"],
68
+ },
69
+ {
70
+ type: "object",
71
+ properties: {
72
+ conditionalAssign: { type: "boolean" },
73
+ ternaryOperandBinaryExpressions: {
74
+ type: "boolean",
75
+ },
76
+ nestedBinaryExpressions: { type: "boolean" },
77
+ returnAssign: { type: "boolean" },
78
+ ignoreJSX: {
79
+ enum: [
80
+ "none",
81
+ "all",
82
+ "single-line",
83
+ "multi-line",
84
+ ],
85
+ },
86
+ enforceForArrowConditionals: {
87
+ type: "boolean",
88
+ },
89
+ enforceForSequenceExpressions: {
90
+ type: "boolean",
91
+ },
92
+ enforceForNewInMemberExpressions: {
93
+ type: "boolean",
94
+ },
95
+ enforceForFunctionPrototypeMethods: {
96
+ type: "boolean",
97
+ },
98
+ allowParensAfterCommentPattern: {
99
+ type: "string",
100
+ },
101
+ },
102
+ additionalProperties: false,
103
+ },
104
+ ],
105
+ minItems: 0,
106
+ maxItems: 2,
107
+ },
108
+ ],
109
+ },
110
+
111
+ messages: {
112
+ unexpected: "Unnecessary parentheses around expression.",
113
+ },
114
+ },
115
+
116
+ create(context) {
117
+ const sourceCode = context.sourceCode;
118
+
119
+ const tokensToIgnore = new WeakSet();
120
+ const precedence = astUtils.getPrecedence;
121
+ const ALL_NODES = context.options[0] !== "functions";
122
+ const EXCEPT_COND_ASSIGN =
123
+ ALL_NODES &&
124
+ context.options[1] &&
125
+ context.options[1].conditionalAssign === false;
126
+ const EXCEPT_COND_TERNARY =
127
+ ALL_NODES &&
128
+ context.options[1] &&
129
+ context.options[1].ternaryOperandBinaryExpressions === false;
130
+ const NESTED_BINARY =
131
+ ALL_NODES &&
132
+ context.options[1] &&
133
+ context.options[1].nestedBinaryExpressions === false;
134
+ const EXCEPT_RETURN_ASSIGN =
135
+ ALL_NODES &&
136
+ context.options[1] &&
137
+ context.options[1].returnAssign === false;
138
+ const IGNORE_JSX =
139
+ ALL_NODES && context.options[1] && context.options[1].ignoreJSX;
140
+ const IGNORE_ARROW_CONDITIONALS =
141
+ ALL_NODES &&
142
+ context.options[1] &&
143
+ context.options[1].enforceForArrowConditionals === false;
144
+ const IGNORE_SEQUENCE_EXPRESSIONS =
145
+ ALL_NODES &&
146
+ context.options[1] &&
147
+ context.options[1].enforceForSequenceExpressions === false;
148
+ const IGNORE_NEW_IN_MEMBER_EXPR =
149
+ ALL_NODES &&
150
+ context.options[1] &&
151
+ context.options[1].enforceForNewInMemberExpressions === false;
152
+ const IGNORE_FUNCTION_PROTOTYPE_METHODS =
153
+ ALL_NODES &&
154
+ context.options[1] &&
155
+ context.options[1].enforceForFunctionPrototypeMethods === false;
156
+ const ALLOW_PARENS_AFTER_COMMENT_PATTERN =
157
+ ALL_NODES &&
158
+ context.options[1] &&
159
+ context.options[1].allowParensAfterCommentPattern;
160
+
161
+ const PRECEDENCE_OF_ASSIGNMENT_EXPR = precedence({
162
+ type: "AssignmentExpression",
163
+ });
164
+ const PRECEDENCE_OF_UPDATE_EXPR = precedence({
165
+ type: "UpdateExpression",
166
+ });
167
+
168
+ let reportsBuffer;
169
+
170
+ /**
171
+ * Determines whether the given node is a `call` or `apply` method call, invoked directly on a `FunctionExpression` node.
172
+ * Example: function(){}.call()
173
+ * @param {ASTNode} node The node to be checked.
174
+ * @returns {boolean} True if the node is an immediate `call` or `apply` method call.
175
+ * @private
176
+ */
177
+ function isImmediateFunctionPrototypeMethodCall(node) {
178
+ const callNode = astUtils.skipChainExpression(node);
179
+
180
+ if (callNode.type !== "CallExpression") {
181
+ return false;
182
+ }
183
+ const callee = astUtils.skipChainExpression(callNode.callee);
184
+
185
+ return (
186
+ callee.type === "MemberExpression" &&
187
+ callee.object.type === "FunctionExpression" &&
188
+ ["call", "apply"].includes(
189
+ astUtils.getStaticPropertyName(callee),
190
+ )
191
+ );
192
+ }
193
+
194
+ /**
195
+ * Determines if this rule should be enforced for a node given the current configuration.
196
+ * @param {ASTNode} node The node to be checked.
197
+ * @returns {boolean} True if the rule should be enforced for this node.
198
+ * @private
199
+ */
200
+ function ruleApplies(node) {
201
+ if (node.type === "JSXElement" || node.type === "JSXFragment") {
202
+ const isSingleLine = node.loc.start.line === node.loc.end.line;
203
+
204
+ switch (IGNORE_JSX) {
205
+ // Exclude this JSX element from linting
206
+ case "all":
207
+ return false;
208
+
209
+ // Exclude this JSX element if it is multi-line element
210
+ case "multi-line":
211
+ return isSingleLine;
212
+
213
+ // Exclude this JSX element if it is single-line element
214
+ case "single-line":
215
+ return !isSingleLine;
216
+
217
+ // Nothing special to be done for JSX elements
218
+ case "none":
219
+ break;
220
+
221
+ // no default
222
+ }
223
+ }
224
+
225
+ if (
226
+ node.type === "SequenceExpression" &&
227
+ IGNORE_SEQUENCE_EXPRESSIONS
228
+ ) {
229
+ return false;
230
+ }
231
+
232
+ if (
233
+ isImmediateFunctionPrototypeMethodCall(node) &&
234
+ IGNORE_FUNCTION_PROTOTYPE_METHODS
235
+ ) {
236
+ return false;
237
+ }
238
+
239
+ return (
240
+ ALL_NODES ||
241
+ node.type === "FunctionExpression" ||
242
+ node.type === "ArrowFunctionExpression"
243
+ );
244
+ }
245
+
246
+ /**
247
+ * Determines if a node is surrounded by parentheses.
248
+ * @param {ASTNode} node The node to be checked.
249
+ * @returns {boolean} True if the node is parenthesised.
250
+ * @private
251
+ */
252
+ function isParenthesised(node) {
253
+ return isParenthesizedRaw(1, node, sourceCode);
254
+ }
255
+
256
+ /**
257
+ * Determines if a node is surrounded by parentheses twice.
258
+ * @param {ASTNode} node The node to be checked.
259
+ * @returns {boolean} True if the node is doubly parenthesised.
260
+ * @private
261
+ */
262
+ function isParenthesisedTwice(node) {
263
+ return isParenthesizedRaw(2, node, sourceCode);
264
+ }
265
+
266
+ /**
267
+ * Determines if a node is surrounded by (potentially) invalid parentheses.
268
+ * @param {ASTNode} node The node to be checked.
269
+ * @returns {boolean} True if the node is incorrectly parenthesised.
270
+ * @private
271
+ */
272
+ function hasExcessParens(node) {
273
+ return ruleApplies(node) && isParenthesised(node);
274
+ }
275
+
276
+ /**
277
+ * Determines if a node that is expected to be parenthesised is surrounded by
278
+ * (potentially) invalid extra parentheses.
279
+ * @param {ASTNode} node The node to be checked.
280
+ * @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
281
+ * @private
282
+ */
283
+ function hasDoubleExcessParens(node) {
284
+ return ruleApplies(node) && isParenthesisedTwice(node);
285
+ }
286
+
287
+ /**
288
+ * Determines if a node that is expected to be parenthesised is surrounded by
289
+ * (potentially) invalid extra parentheses with considering precedence level of the node.
290
+ * If the preference level of the node is not higher or equal to precedence lower limit, it also checks
291
+ * whether the node is surrounded by parentheses twice or not.
292
+ * @param {ASTNode} node The node to be checked.
293
+ * @param {number} precedenceLowerLimit The lower limit of precedence.
294
+ * @returns {boolean} True if the node is has an unexpected extra pair of parentheses.
295
+ * @private
296
+ */
297
+ function hasExcessParensWithPrecedence(node, precedenceLowerLimit) {
298
+ if (ruleApplies(node) && isParenthesised(node)) {
299
+ if (
300
+ precedence(node) >= precedenceLowerLimit ||
301
+ isParenthesisedTwice(node)
302
+ ) {
303
+ return true;
304
+ }
305
+ }
306
+ return false;
307
+ }
308
+
309
+ /**
310
+ * Determines if a node test expression is allowed to have a parenthesised assignment
311
+ * @param {ASTNode} node The node to be checked.
312
+ * @returns {boolean} True if the assignment can be parenthesised.
313
+ * @private
314
+ */
315
+ function isCondAssignException(node) {
316
+ return (
317
+ EXCEPT_COND_ASSIGN && node.test.type === "AssignmentExpression"
318
+ );
319
+ }
320
+
321
+ /**
322
+ * Determines if a node is in a return statement
323
+ * @param {ASTNode} node The node to be checked.
324
+ * @returns {boolean} True if the node is in a return statement.
325
+ * @private
326
+ */
327
+ function isInReturnStatement(node) {
328
+ for (
329
+ let currentNode = node;
330
+ currentNode;
331
+ currentNode = currentNode.parent
332
+ ) {
333
+ if (
334
+ currentNode.type === "ReturnStatement" ||
335
+ (currentNode.type === "ArrowFunctionExpression" &&
336
+ currentNode.body.type !== "BlockStatement")
337
+ ) {
338
+ return true;
339
+ }
340
+ }
341
+
342
+ return false;
343
+ }
344
+
345
+ /**
346
+ * Determines if a constructor function is newed-up with parens
347
+ * @param {ASTNode} newExpression The NewExpression node to be checked.
348
+ * @returns {boolean} True if the constructor is called with parens.
349
+ * @private
350
+ */
351
+ function isNewExpressionWithParens(newExpression) {
352
+ const lastToken = sourceCode.getLastToken(newExpression);
353
+ const penultimateToken = sourceCode.getTokenBefore(lastToken);
354
+
355
+ return (
356
+ newExpression.arguments.length > 0 ||
357
+ // The expression should end with its own parens, e.g., new new foo() is not a new expression with parens
358
+ (astUtils.isOpeningParenToken(penultimateToken) &&
359
+ astUtils.isClosingParenToken(lastToken) &&
360
+ newExpression.callee.range[1] < newExpression.range[1])
361
+ );
362
+ }
363
+
364
+ /**
365
+ * Determines if a node is or contains an assignment expression
366
+ * @param {ASTNode} node The node to be checked.
367
+ * @returns {boolean} True if the node is or contains an assignment expression.
368
+ * @private
369
+ */
370
+ function containsAssignment(node) {
371
+ if (node.type === "AssignmentExpression") {
372
+ return true;
373
+ }
374
+ if (
375
+ node.type === "ConditionalExpression" &&
376
+ (node.consequent.type === "AssignmentExpression" ||
377
+ node.alternate.type === "AssignmentExpression")
378
+ ) {
379
+ return true;
380
+ }
381
+ if (
382
+ (node.left && node.left.type === "AssignmentExpression") ||
383
+ (node.right && node.right.type === "AssignmentExpression")
384
+ ) {
385
+ return true;
386
+ }
387
+
388
+ return false;
389
+ }
390
+
391
+ /**
392
+ * Determines if a node is contained by or is itself a return statement and is allowed to have a parenthesised assignment
393
+ * @param {ASTNode} node The node to be checked.
394
+ * @returns {boolean} True if the assignment can be parenthesised.
395
+ * @private
396
+ */
397
+ function isReturnAssignException(node) {
398
+ if (!EXCEPT_RETURN_ASSIGN || !isInReturnStatement(node)) {
399
+ return false;
400
+ }
401
+
402
+ if (node.type === "ReturnStatement") {
403
+ return node.argument && containsAssignment(node.argument);
404
+ }
405
+ if (
406
+ node.type === "ArrowFunctionExpression" &&
407
+ node.body.type !== "BlockStatement"
408
+ ) {
409
+ return containsAssignment(node.body);
410
+ }
411
+ return containsAssignment(node);
412
+ }
413
+
414
+ /**
415
+ * Determines if a node following a [no LineTerminator here] restriction is
416
+ * surrounded by (potentially) invalid extra parentheses.
417
+ * @param {Token} token The token preceding the [no LineTerminator here] restriction.
418
+ * @param {ASTNode} node The node to be checked.
419
+ * @returns {boolean} True if the node is incorrectly parenthesised.
420
+ * @private
421
+ */
422
+ function hasExcessParensNoLineTerminator(token, node) {
423
+ if (token.loc.end.line === node.loc.start.line) {
424
+ return hasExcessParens(node);
425
+ }
426
+
427
+ return hasDoubleExcessParens(node);
428
+ }
429
+
430
+ /**
431
+ * Determines whether a node should be preceded by an additional space when removing parens
432
+ * @param {ASTNode} node node to evaluate; must be surrounded by parentheses
433
+ * @returns {boolean} `true` if a space should be inserted before the node
434
+ * @private
435
+ */
436
+ function requiresLeadingSpace(node) {
437
+ const leftParenToken = sourceCode.getTokenBefore(node);
438
+ const tokenBeforeLeftParen = sourceCode.getTokenBefore(
439
+ leftParenToken,
440
+ { includeComments: true },
441
+ );
442
+ const tokenAfterLeftParen = sourceCode.getTokenAfter(
443
+ leftParenToken,
444
+ { includeComments: true },
445
+ );
446
+
447
+ return (
448
+ tokenBeforeLeftParen &&
449
+ tokenBeforeLeftParen.range[1] === leftParenToken.range[0] &&
450
+ leftParenToken.range[1] === tokenAfterLeftParen.range[0] &&
451
+ !astUtils.canTokensBeAdjacent(
452
+ tokenBeforeLeftParen,
453
+ tokenAfterLeftParen,
454
+ )
455
+ );
456
+ }
457
+
458
+ /**
459
+ * Determines whether a node should be followed by an additional space when removing parens
460
+ * @param {ASTNode} node node to evaluate; must be surrounded by parentheses
461
+ * @returns {boolean} `true` if a space should be inserted after the node
462
+ * @private
463
+ */
464
+ function requiresTrailingSpace(node) {
465
+ const nextTwoTokens = sourceCode.getTokensAfter(node, { count: 2 });
466
+ const rightParenToken = nextTwoTokens[0];
467
+ const tokenAfterRightParen = nextTwoTokens[1];
468
+ const tokenBeforeRightParen = sourceCode.getLastToken(node);
469
+
470
+ return (
471
+ rightParenToken &&
472
+ tokenAfterRightParen &&
473
+ !sourceCode.isSpaceBetweenTokens(
474
+ rightParenToken,
475
+ tokenAfterRightParen,
476
+ ) &&
477
+ !astUtils.canTokensBeAdjacent(
478
+ tokenBeforeRightParen,
479
+ tokenAfterRightParen,
480
+ )
481
+ );
482
+ }
483
+
484
+ /**
485
+ * Determines if a given expression node is an IIFE
486
+ * @param {ASTNode} node The node to check
487
+ * @returns {boolean} `true` if the given node is an IIFE
488
+ */
489
+ function isIIFE(node) {
490
+ const maybeCallNode = astUtils.skipChainExpression(node);
491
+
492
+ return (
493
+ maybeCallNode.type === "CallExpression" &&
494
+ maybeCallNode.callee.type === "FunctionExpression"
495
+ );
496
+ }
497
+
498
+ /**
499
+ * Determines if the given node can be the assignment target in destructuring or the LHS of an assignment.
500
+ * This is to avoid an autofix that could change behavior because parsers mistakenly allow invalid syntax,
501
+ * such as `(a = b) = c` and `[(a = b) = c] = []`. Ideally, this function shouldn't be necessary.
502
+ * @param {ASTNode} [node] The node to check
503
+ * @returns {boolean} `true` if the given node can be a valid assignment target
504
+ */
505
+ function canBeAssignmentTarget(node) {
506
+ return (
507
+ node &&
508
+ (node.type === "Identifier" || node.type === "MemberExpression")
509
+ );
510
+ }
511
+
512
+ /**
513
+ * Checks if a node is fixable.
514
+ * A node is fixable if removing a single pair of surrounding parentheses does not turn it
515
+ * into a directive after fixing other nodes.
516
+ * Almost all nodes are fixable, except if all of the following conditions are met:
517
+ * The node is a string Literal
518
+ * It has a single pair of parentheses
519
+ * It is the only child of an ExpressionStatement
520
+ * @param {ASTNode} node The node to evaluate.
521
+ * @returns {boolean} Whether or not the node is fixable.
522
+ * @private
523
+ */
524
+ function isFixable(node) {
525
+ // if it's not a string literal it can be autofixed
526
+ if (node.type !== "Literal" || typeof node.value !== "string") {
527
+ return true;
528
+ }
529
+ if (isParenthesisedTwice(node)) {
530
+ return true;
531
+ }
532
+ return !astUtils.isTopLevelExpressionStatement(node.parent);
533
+ }
534
+
535
+ /**
536
+ * Report the node
537
+ * @param {ASTNode} node node to evaluate
538
+ * @returns {void}
539
+ * @private
540
+ */
541
+ function report(node) {
542
+ const leftParenToken = sourceCode.getTokenBefore(node);
543
+ const rightParenToken = sourceCode.getTokenAfter(node);
544
+
545
+ if (!isParenthesisedTwice(node)) {
546
+ if (tokensToIgnore.has(sourceCode.getFirstToken(node))) {
547
+ return;
548
+ }
549
+
550
+ if (isIIFE(node) && !isParenthesised(node.callee)) {
551
+ return;
552
+ }
553
+
554
+ if (ALLOW_PARENS_AFTER_COMMENT_PATTERN) {
555
+ const commentsBeforeLeftParenToken =
556
+ sourceCode.getCommentsBefore(leftParenToken);
557
+ const totalCommentsBeforeLeftParenTokenCount =
558
+ commentsBeforeLeftParenToken.length;
559
+ const ignorePattern = new RegExp(
560
+ ALLOW_PARENS_AFTER_COMMENT_PATTERN,
561
+ "u",
562
+ );
563
+
564
+ if (
565
+ totalCommentsBeforeLeftParenTokenCount > 0 &&
566
+ ignorePattern.test(
567
+ commentsBeforeLeftParenToken[
568
+ totalCommentsBeforeLeftParenTokenCount - 1
569
+ ].value,
570
+ )
571
+ ) {
572
+ return;
573
+ }
574
+ }
575
+ }
576
+
577
+ /**
578
+ * Finishes reporting
579
+ * @returns {void}
580
+ * @private
581
+ */
582
+ function finishReport() {
583
+ context.report({
584
+ node,
585
+ loc: leftParenToken.loc,
586
+ messageId: "unexpected",
587
+ fix: isFixable(node)
588
+ ? fixer => {
589
+ const parenthesizedSource =
590
+ sourceCode.text.slice(
591
+ leftParenToken.range[1],
592
+ rightParenToken.range[0],
593
+ );
594
+
595
+ return fixer.replaceTextRange(
596
+ [
597
+ leftParenToken.range[0],
598
+ rightParenToken.range[1],
599
+ ],
600
+ (requiresLeadingSpace(node) ? " " : "") +
601
+ parenthesizedSource +
602
+ (requiresTrailingSpace(node)
603
+ ? " "
604
+ : ""),
605
+ );
606
+ }
607
+ : null,
608
+ });
609
+ }
610
+
611
+ if (reportsBuffer) {
612
+ reportsBuffer.reports.push({ node, finishReport });
613
+ return;
614
+ }
615
+
616
+ finishReport();
617
+ }
618
+
619
+ /**
620
+ * Evaluate a argument of the node.
621
+ * @param {ASTNode} node node to evaluate
622
+ * @returns {void}
623
+ * @private
624
+ */
625
+ function checkArgumentWithPrecedence(node) {
626
+ if (
627
+ hasExcessParensWithPrecedence(node.argument, precedence(node))
628
+ ) {
629
+ report(node.argument);
630
+ }
631
+ }
632
+
633
+ /**
634
+ * Check if a member expression contains a call expression
635
+ * @param {ASTNode} node MemberExpression node to evaluate
636
+ * @returns {boolean} true if found, false if not
637
+ */
638
+ function doesMemberExpressionContainCallExpression(node) {
639
+ let currentNode = node.object;
640
+ let currentNodeType = node.object.type;
641
+
642
+ while (currentNodeType === "MemberExpression") {
643
+ currentNode = currentNode.object;
644
+ currentNodeType = currentNode.type;
645
+ }
646
+
647
+ return currentNodeType === "CallExpression";
648
+ }
649
+
650
+ /**
651
+ * Evaluate a new call
652
+ * @param {ASTNode} node node to evaluate
653
+ * @returns {void}
654
+ * @private
655
+ */
656
+ function checkCallNew(node) {
657
+ const callee = node.callee;
658
+
659
+ if (hasExcessParensWithPrecedence(callee, precedence(node))) {
660
+ if (
661
+ hasDoubleExcessParens(callee) ||
662
+ !(
663
+ isIIFE(node) ||
664
+ // (new A)(); new (new A)();
665
+ (callee.type === "NewExpression" &&
666
+ !isNewExpressionWithParens(callee) &&
667
+ !(
668
+ node.type === "NewExpression" &&
669
+ !isNewExpressionWithParens(node)
670
+ )) ||
671
+ // new (a().b)(); new (a.b().c);
672
+ (node.type === "NewExpression" &&
673
+ callee.type === "MemberExpression" &&
674
+ doesMemberExpressionContainCallExpression(
675
+ callee,
676
+ )) ||
677
+ // (a?.b)(); (a?.())();
678
+ (!node.optional && callee.type === "ChainExpression")
679
+ )
680
+ ) {
681
+ report(node.callee);
682
+ }
683
+ }
684
+ node.arguments
685
+ .filter(arg =>
686
+ hasExcessParensWithPrecedence(
687
+ arg,
688
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
689
+ ),
690
+ )
691
+ .forEach(report);
692
+ }
693
+
694
+ /**
695
+ * Evaluate binary logicals
696
+ * @param {ASTNode} node node to evaluate
697
+ * @returns {void}
698
+ * @private
699
+ */
700
+ function checkBinaryLogical(node) {
701
+ const prec = precedence(node);
702
+ const leftPrecedence = precedence(node.left);
703
+ const rightPrecedence = precedence(node.right);
704
+ const isExponentiation = node.operator === "**";
705
+ const shouldSkipLeft =
706
+ NESTED_BINARY &&
707
+ (node.left.type === "BinaryExpression" ||
708
+ node.left.type === "LogicalExpression");
709
+ const shouldSkipRight =
710
+ NESTED_BINARY &&
711
+ (node.right.type === "BinaryExpression" ||
712
+ node.right.type === "LogicalExpression");
713
+
714
+ if (!shouldSkipLeft && hasExcessParens(node.left)) {
715
+ if (
716
+ (!(
717
+ ["AwaitExpression", "UnaryExpression"].includes(
718
+ node.left.type,
719
+ ) && isExponentiation
720
+ ) &&
721
+ !astUtils.isMixedLogicalAndCoalesceExpressions(
722
+ node.left,
723
+ node,
724
+ ) &&
725
+ (leftPrecedence > prec ||
726
+ (leftPrecedence === prec && !isExponentiation))) ||
727
+ isParenthesisedTwice(node.left)
728
+ ) {
729
+ report(node.left);
730
+ }
731
+ }
732
+
733
+ if (!shouldSkipRight && hasExcessParens(node.right)) {
734
+ if (
735
+ (!astUtils.isMixedLogicalAndCoalesceExpressions(
736
+ node.right,
737
+ node,
738
+ ) &&
739
+ (rightPrecedence > prec ||
740
+ (rightPrecedence === prec && isExponentiation))) ||
741
+ isParenthesisedTwice(node.right)
742
+ ) {
743
+ report(node.right);
744
+ }
745
+ }
746
+ }
747
+
748
+ /**
749
+ * Check the parentheses around the super class of the given class definition.
750
+ * @param {ASTNode} node The node of class declarations to check.
751
+ * @returns {void}
752
+ */
753
+ function checkClass(node) {
754
+ if (!node.superClass) {
755
+ return;
756
+ }
757
+
758
+ /*
759
+ * If `node.superClass` is a LeftHandSideExpression, parentheses are extra.
760
+ * Otherwise, parentheses are needed.
761
+ */
762
+ const hasExtraParens =
763
+ precedence(node.superClass) > PRECEDENCE_OF_UPDATE_EXPR
764
+ ? hasExcessParens(node.superClass)
765
+ : hasDoubleExcessParens(node.superClass);
766
+
767
+ if (hasExtraParens) {
768
+ report(node.superClass);
769
+ }
770
+ }
771
+
772
+ /**
773
+ * Check the parentheses around the argument of the given spread operator.
774
+ * @param {ASTNode} node The node of spread elements/properties to check.
775
+ * @returns {void}
776
+ */
777
+ function checkSpreadOperator(node) {
778
+ if (
779
+ hasExcessParensWithPrecedence(
780
+ node.argument,
781
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
782
+ )
783
+ ) {
784
+ report(node.argument);
785
+ }
786
+ }
787
+
788
+ /**
789
+ * Checks the parentheses for an ExpressionStatement or ExportDefaultDeclaration
790
+ * @param {ASTNode} node The ExpressionStatement.expression or ExportDefaultDeclaration.declaration node
791
+ * @returns {void}
792
+ */
793
+ function checkExpressionOrExportStatement(node) {
794
+ const firstToken = isParenthesised(node)
795
+ ? sourceCode.getTokenBefore(node)
796
+ : sourceCode.getFirstToken(node);
797
+ const secondToken = sourceCode.getTokenAfter(
798
+ firstToken,
799
+ astUtils.isNotOpeningParenToken,
800
+ );
801
+ const thirdToken = secondToken
802
+ ? sourceCode.getTokenAfter(secondToken)
803
+ : null;
804
+ const tokenAfterClosingParens = secondToken
805
+ ? sourceCode.getTokenAfter(
806
+ secondToken,
807
+ astUtils.isNotClosingParenToken,
808
+ )
809
+ : null;
810
+
811
+ if (
812
+ astUtils.isOpeningParenToken(firstToken) &&
813
+ (astUtils.isOpeningBraceToken(secondToken) ||
814
+ (secondToken.type === "Keyword" &&
815
+ (secondToken.value === "function" ||
816
+ secondToken.value === "class" ||
817
+ (secondToken.value === "let" &&
818
+ tokenAfterClosingParens &&
819
+ (astUtils.isOpeningBracketToken(
820
+ tokenAfterClosingParens,
821
+ ) ||
822
+ tokenAfterClosingParens.type ===
823
+ "Identifier")))) ||
824
+ (secondToken &&
825
+ secondToken.type === "Identifier" &&
826
+ secondToken.value === "async" &&
827
+ thirdToken &&
828
+ thirdToken.type === "Keyword" &&
829
+ thirdToken.value === "function"))
830
+ ) {
831
+ tokensToIgnore.add(secondToken);
832
+ }
833
+
834
+ const hasExtraParens =
835
+ node.parent.type === "ExportDefaultDeclaration"
836
+ ? hasExcessParensWithPrecedence(
837
+ node,
838
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
839
+ )
840
+ : hasExcessParens(node);
841
+
842
+ if (hasExtraParens) {
843
+ report(node);
844
+ }
845
+ }
846
+
847
+ /**
848
+ * Finds the path from the given node to the specified ancestor.
849
+ * @param {ASTNode} node First node in the path.
850
+ * @param {ASTNode} ancestor Last node in the path.
851
+ * @returns {ASTNode[]} Path, including both nodes.
852
+ * @throws {Error} If the given node does not have the specified ancestor.
853
+ */
854
+ function pathToAncestor(node, ancestor) {
855
+ const path = [node];
856
+ let currentNode = node;
857
+
858
+ while (currentNode !== ancestor) {
859
+ currentNode = currentNode.parent;
860
+
861
+ /* c8 ignore start */
862
+ if (currentNode === null) {
863
+ throw new Error(
864
+ "Nodes are not in the ancestor-descendant relationship.",
865
+ );
866
+ } /* c8 ignore stop */
867
+
868
+ path.push(currentNode);
869
+ }
870
+
871
+ return path;
872
+ }
873
+
874
+ /**
875
+ * Finds the path from the given node to the specified descendant.
876
+ * @param {ASTNode} node First node in the path.
877
+ * @param {ASTNode} descendant Last node in the path.
878
+ * @returns {ASTNode[]} Path, including both nodes.
879
+ * @throws {Error} If the given node does not have the specified descendant.
880
+ */
881
+ function pathToDescendant(node, descendant) {
882
+ return pathToAncestor(descendant, node).reverse();
883
+ }
884
+
885
+ /**
886
+ * Checks whether the syntax of the given ancestor of an 'in' expression inside a for-loop initializer
887
+ * is preventing the 'in' keyword from being interpreted as a part of an ill-formed for-in loop.
888
+ * @param {ASTNode} node Ancestor of an 'in' expression.
889
+ * @param {ASTNode} child Child of the node, ancestor of the same 'in' expression or the 'in' expression itself.
890
+ * @returns {boolean} True if the keyword 'in' would be interpreted as the 'in' operator, without any parenthesis.
891
+ */
892
+ function isSafelyEnclosingInExpression(node, child) {
893
+ switch (node.type) {
894
+ case "ArrayExpression":
895
+ case "ArrayPattern":
896
+ case "BlockStatement":
897
+ case "ObjectExpression":
898
+ case "ObjectPattern":
899
+ case "TemplateLiteral":
900
+ return true;
901
+ case "ArrowFunctionExpression":
902
+ case "FunctionExpression":
903
+ return node.params.includes(child);
904
+ case "CallExpression":
905
+ case "NewExpression":
906
+ return node.arguments.includes(child);
907
+ case "MemberExpression":
908
+ return node.computed && node.property === child;
909
+ case "ConditionalExpression":
910
+ return node.consequent === child;
911
+ default:
912
+ return false;
913
+ }
914
+ }
915
+
916
+ /**
917
+ * Starts a new reports buffering. Warnings will be stored in a buffer instead of being reported immediately.
918
+ * An additional logic that requires multiple nodes (e.g. a whole subtree) may dismiss some of the stored warnings.
919
+ * @returns {void}
920
+ */
921
+ function startNewReportsBuffering() {
922
+ reportsBuffer = {
923
+ upper: reportsBuffer,
924
+ inExpressionNodes: [],
925
+ reports: [],
926
+ };
927
+ }
928
+
929
+ /**
930
+ * Ends the current reports buffering.
931
+ * @returns {void}
932
+ */
933
+ function endCurrentReportsBuffering() {
934
+ const { upper, inExpressionNodes, reports } = reportsBuffer;
935
+
936
+ if (upper) {
937
+ upper.inExpressionNodes.push(...inExpressionNodes);
938
+ upper.reports.push(...reports);
939
+ } else {
940
+ // flush remaining reports
941
+ reports.forEach(({ finishReport }) => finishReport());
942
+ }
943
+
944
+ reportsBuffer = upper;
945
+ }
946
+
947
+ /**
948
+ * Checks whether the given node is in the current reports buffer.
949
+ * @param {ASTNode} node Node to check.
950
+ * @returns {boolean} True if the node is in the current buffer, false otherwise.
951
+ */
952
+ function isInCurrentReportsBuffer(node) {
953
+ return reportsBuffer.reports.some(r => r.node === node);
954
+ }
955
+
956
+ /**
957
+ * Removes the given node from the current reports buffer.
958
+ * @param {ASTNode} node Node to remove.
959
+ * @returns {void}
960
+ */
961
+ function removeFromCurrentReportsBuffer(node) {
962
+ reportsBuffer.reports = reportsBuffer.reports.filter(
963
+ r => r.node !== node,
964
+ );
965
+ }
966
+
967
+ /**
968
+ * Checks whether a node is a MemberExpression at NewExpression's callee.
969
+ * @param {ASTNode} node node to check.
970
+ * @returns {boolean} True if the node is a MemberExpression at NewExpression's callee. false otherwise.
971
+ */
972
+ function isMemberExpInNewCallee(node) {
973
+ if (node.type === "MemberExpression") {
974
+ return node.parent.type === "NewExpression" &&
975
+ node.parent.callee === node
976
+ ? true
977
+ : node.parent.object === node &&
978
+ isMemberExpInNewCallee(node.parent);
979
+ }
980
+ return false;
981
+ }
982
+
983
+ /**
984
+ * Checks if the left-hand side of an assignment is an identifier, the operator is one of
985
+ * `=`, `&&=`, `||=` or `??=` and the right-hand side is an anonymous class or function.
986
+ *
987
+ * As per https://tc39.es/ecma262/#sec-assignment-operators-runtime-semantics-evaluation, an
988
+ * assignment involving one of the operators `=`, `&&=`, `||=` or `??=` where the right-hand
989
+ * side is an anonymous class or function and the left-hand side is an *unparenthesized*
990
+ * identifier has different semantics than other assignments.
991
+ * Specifically, when an expression like `foo = function () {}` is evaluated, `foo.name`
992
+ * will be set to the string "foo", i.e. the identifier name. The same thing does not happen
993
+ * when evaluating `(foo) = function () {}`.
994
+ * Since the parenthesizing of the identifier in the left-hand side is significant in this
995
+ * special case, the parentheses, if present, should not be flagged as unnecessary.
996
+ * @param {ASTNode} node an AssignmentExpression node.
997
+ * @returns {boolean} `true` if the left-hand side of the assignment is an identifier, the
998
+ * operator is one of `=`, `&&=`, `||=` or `??=` and the right-hand side is an anonymous
999
+ * class or function; otherwise, `false`.
1000
+ */
1001
+ function isAnonymousFunctionAssignmentException({
1002
+ left,
1003
+ operator,
1004
+ right,
1005
+ }) {
1006
+ if (
1007
+ left.type === "Identifier" &&
1008
+ ["=", "&&=", "||=", "??="].includes(operator)
1009
+ ) {
1010
+ const rhsType = right.type;
1011
+
1012
+ if (rhsType === "ArrowFunctionExpression") {
1013
+ return true;
1014
+ }
1015
+ if (
1016
+ (rhsType === "FunctionExpression" ||
1017
+ rhsType === "ClassExpression") &&
1018
+ !right.id
1019
+ ) {
1020
+ return true;
1021
+ }
1022
+ }
1023
+ return false;
1024
+ }
1025
+
1026
+ return {
1027
+ ArrayExpression(node) {
1028
+ node.elements
1029
+ .filter(
1030
+ e =>
1031
+ e &&
1032
+ hasExcessParensWithPrecedence(
1033
+ e,
1034
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1035
+ ),
1036
+ )
1037
+ .forEach(report);
1038
+ },
1039
+
1040
+ ArrayPattern(node) {
1041
+ node.elements
1042
+ .filter(e => canBeAssignmentTarget(e) && hasExcessParens(e))
1043
+ .forEach(report);
1044
+ },
1045
+
1046
+ ArrowFunctionExpression(node) {
1047
+ if (isReturnAssignException(node)) {
1048
+ return;
1049
+ }
1050
+
1051
+ if (
1052
+ node.body.type === "ConditionalExpression" &&
1053
+ IGNORE_ARROW_CONDITIONALS
1054
+ ) {
1055
+ return;
1056
+ }
1057
+
1058
+ if (node.body.type !== "BlockStatement") {
1059
+ const firstBodyToken = sourceCode.getFirstToken(
1060
+ node.body,
1061
+ astUtils.isNotOpeningParenToken,
1062
+ );
1063
+ const tokenBeforeFirst =
1064
+ sourceCode.getTokenBefore(firstBodyToken);
1065
+
1066
+ if (
1067
+ astUtils.isOpeningParenToken(tokenBeforeFirst) &&
1068
+ astUtils.isOpeningBraceToken(firstBodyToken)
1069
+ ) {
1070
+ tokensToIgnore.add(firstBodyToken);
1071
+ }
1072
+ if (
1073
+ hasExcessParensWithPrecedence(
1074
+ node.body,
1075
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1076
+ )
1077
+ ) {
1078
+ report(node.body);
1079
+ }
1080
+ }
1081
+ },
1082
+
1083
+ AssignmentExpression(node) {
1084
+ if (
1085
+ canBeAssignmentTarget(node.left) &&
1086
+ hasExcessParens(node.left) &&
1087
+ (!isAnonymousFunctionAssignmentException(node) ||
1088
+ isParenthesisedTwice(node.left))
1089
+ ) {
1090
+ report(node.left);
1091
+ }
1092
+
1093
+ if (
1094
+ !isReturnAssignException(node) &&
1095
+ hasExcessParensWithPrecedence(node.right, precedence(node))
1096
+ ) {
1097
+ report(node.right);
1098
+ }
1099
+ },
1100
+
1101
+ BinaryExpression(node) {
1102
+ if (reportsBuffer && node.operator === "in") {
1103
+ reportsBuffer.inExpressionNodes.push(node);
1104
+ }
1105
+
1106
+ checkBinaryLogical(node);
1107
+ },
1108
+
1109
+ CallExpression: checkCallNew,
1110
+
1111
+ ConditionalExpression(node) {
1112
+ if (isReturnAssignException(node)) {
1113
+ return;
1114
+ }
1115
+
1116
+ const availableTypes = new Set([
1117
+ "BinaryExpression",
1118
+ "LogicalExpression",
1119
+ ]);
1120
+
1121
+ if (
1122
+ !(
1123
+ EXCEPT_COND_TERNARY &&
1124
+ availableTypes.has(node.test.type)
1125
+ ) &&
1126
+ !isCondAssignException(node) &&
1127
+ hasExcessParensWithPrecedence(
1128
+ node.test,
1129
+ precedence({
1130
+ type: "LogicalExpression",
1131
+ operator: "||",
1132
+ }),
1133
+ )
1134
+ ) {
1135
+ report(node.test);
1136
+ }
1137
+
1138
+ if (
1139
+ !(
1140
+ EXCEPT_COND_TERNARY &&
1141
+ availableTypes.has(node.consequent.type)
1142
+ ) &&
1143
+ hasExcessParensWithPrecedence(
1144
+ node.consequent,
1145
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1146
+ )
1147
+ ) {
1148
+ report(node.consequent);
1149
+ }
1150
+
1151
+ if (
1152
+ !(
1153
+ EXCEPT_COND_TERNARY &&
1154
+ availableTypes.has(node.alternate.type)
1155
+ ) &&
1156
+ hasExcessParensWithPrecedence(
1157
+ node.alternate,
1158
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1159
+ )
1160
+ ) {
1161
+ report(node.alternate);
1162
+ }
1163
+ },
1164
+
1165
+ DoWhileStatement(node) {
1166
+ if (
1167
+ hasExcessParens(node.test) &&
1168
+ !isCondAssignException(node)
1169
+ ) {
1170
+ report(node.test);
1171
+ }
1172
+ },
1173
+
1174
+ ExportDefaultDeclaration: node =>
1175
+ checkExpressionOrExportStatement(node.declaration),
1176
+ ExpressionStatement: node =>
1177
+ checkExpressionOrExportStatement(node.expression),
1178
+
1179
+ ForInStatement(node) {
1180
+ if (node.left.type !== "VariableDeclaration") {
1181
+ const firstLeftToken = sourceCode.getFirstToken(
1182
+ node.left,
1183
+ astUtils.isNotOpeningParenToken,
1184
+ );
1185
+
1186
+ if (
1187
+ firstLeftToken.value === "let" &&
1188
+ astUtils.isOpeningBracketToken(
1189
+ sourceCode.getTokenAfter(
1190
+ firstLeftToken,
1191
+ astUtils.isNotClosingParenToken,
1192
+ ),
1193
+ )
1194
+ ) {
1195
+ // ForInStatement#left expression cannot start with `let[`.
1196
+ tokensToIgnore.add(firstLeftToken);
1197
+ }
1198
+ }
1199
+
1200
+ if (hasExcessParens(node.left)) {
1201
+ report(node.left);
1202
+ }
1203
+
1204
+ if (hasExcessParens(node.right)) {
1205
+ report(node.right);
1206
+ }
1207
+ },
1208
+
1209
+ ForOfStatement(node) {
1210
+ if (node.left.type !== "VariableDeclaration") {
1211
+ const firstLeftToken = sourceCode.getFirstToken(
1212
+ node.left,
1213
+ astUtils.isNotOpeningParenToken,
1214
+ );
1215
+
1216
+ if (firstLeftToken.value === "let") {
1217
+ // ForOfStatement#left expression cannot start with `let`.
1218
+ tokensToIgnore.add(firstLeftToken);
1219
+ }
1220
+ }
1221
+
1222
+ if (hasExcessParens(node.left)) {
1223
+ report(node.left);
1224
+ }
1225
+
1226
+ if (
1227
+ hasExcessParensWithPrecedence(
1228
+ node.right,
1229
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1230
+ )
1231
+ ) {
1232
+ report(node.right);
1233
+ }
1234
+ },
1235
+
1236
+ ForStatement(node) {
1237
+ if (
1238
+ node.test &&
1239
+ hasExcessParens(node.test) &&
1240
+ !isCondAssignException(node)
1241
+ ) {
1242
+ report(node.test);
1243
+ }
1244
+
1245
+ if (node.update && hasExcessParens(node.update)) {
1246
+ report(node.update);
1247
+ }
1248
+
1249
+ if (node.init) {
1250
+ if (node.init.type !== "VariableDeclaration") {
1251
+ const firstToken = sourceCode.getFirstToken(
1252
+ node.init,
1253
+ astUtils.isNotOpeningParenToken,
1254
+ );
1255
+
1256
+ if (
1257
+ firstToken.value === "let" &&
1258
+ astUtils.isOpeningBracketToken(
1259
+ sourceCode.getTokenAfter(
1260
+ firstToken,
1261
+ astUtils.isNotClosingParenToken,
1262
+ ),
1263
+ )
1264
+ ) {
1265
+ // ForStatement#init expression cannot start with `let[`.
1266
+ tokensToIgnore.add(firstToken);
1267
+ }
1268
+ }
1269
+
1270
+ startNewReportsBuffering();
1271
+
1272
+ if (hasExcessParens(node.init)) {
1273
+ report(node.init);
1274
+ }
1275
+ }
1276
+ },
1277
+
1278
+ "ForStatement > *.init:exit"(node) {
1279
+ /*
1280
+ * Removing parentheses around `in` expressions might change semantics and cause errors.
1281
+ *
1282
+ * For example, this valid for loop:
1283
+ * for (let a = (b in c); ;);
1284
+ * after removing parentheses would be treated as an invalid for-in loop:
1285
+ * for (let a = b in c; ;);
1286
+ */
1287
+
1288
+ if (reportsBuffer.reports.length) {
1289
+ reportsBuffer.inExpressionNodes.forEach(
1290
+ inExpressionNode => {
1291
+ const path = pathToDescendant(
1292
+ node,
1293
+ inExpressionNode,
1294
+ );
1295
+ let nodeToExclude;
1296
+
1297
+ for (let i = 0; i < path.length; i++) {
1298
+ const pathNode = path[i];
1299
+
1300
+ if (i < path.length - 1) {
1301
+ const nextPathNode = path[i + 1];
1302
+
1303
+ if (
1304
+ isSafelyEnclosingInExpression(
1305
+ pathNode,
1306
+ nextPathNode,
1307
+ )
1308
+ ) {
1309
+ // The 'in' expression in safely enclosed by the syntax of its ancestor nodes (e.g. by '{}' or '[]').
1310
+ return;
1311
+ }
1312
+ }
1313
+
1314
+ if (isParenthesised(pathNode)) {
1315
+ if (isInCurrentReportsBuffer(pathNode)) {
1316
+ // This node was supposed to be reported, but parentheses might be necessary.
1317
+
1318
+ if (isParenthesisedTwice(pathNode)) {
1319
+ /*
1320
+ * This node is parenthesised twice, it certainly has at least one pair of `extra` parentheses.
1321
+ * If the --fix option is on, the current fixing iteration will remove only one pair of parentheses.
1322
+ * The remaining pair is safely enclosing the 'in' expression.
1323
+ */
1324
+ return;
1325
+ }
1326
+
1327
+ // Exclude the outermost node only.
1328
+ if (!nodeToExclude) {
1329
+ nodeToExclude = pathNode;
1330
+ }
1331
+
1332
+ // Don't break the loop here, there might be some safe nodes or parentheses that will stay inside.
1333
+ } else {
1334
+ // This node will stay parenthesised, the 'in' expression in safely enclosed by '()'.
1335
+ return;
1336
+ }
1337
+ }
1338
+ }
1339
+
1340
+ // Exclude the node from the list (i.e. treat parentheses as necessary)
1341
+ removeFromCurrentReportsBuffer(nodeToExclude);
1342
+ },
1343
+ );
1344
+ }
1345
+
1346
+ endCurrentReportsBuffering();
1347
+ },
1348
+
1349
+ IfStatement(node) {
1350
+ if (
1351
+ hasExcessParens(node.test) &&
1352
+ !isCondAssignException(node)
1353
+ ) {
1354
+ report(node.test);
1355
+ }
1356
+ },
1357
+
1358
+ ImportExpression(node) {
1359
+ const { source } = node;
1360
+
1361
+ if (source.type === "SequenceExpression") {
1362
+ if (hasDoubleExcessParens(source)) {
1363
+ report(source);
1364
+ }
1365
+ } else if (hasExcessParens(source)) {
1366
+ report(source);
1367
+ }
1368
+ },
1369
+
1370
+ LogicalExpression: checkBinaryLogical,
1371
+
1372
+ MemberExpression(node) {
1373
+ const shouldAllowWrapOnce =
1374
+ isMemberExpInNewCallee(node) &&
1375
+ doesMemberExpressionContainCallExpression(node);
1376
+ const nodeObjHasExcessParens = shouldAllowWrapOnce
1377
+ ? hasDoubleExcessParens(node.object)
1378
+ : hasExcessParens(node.object) &&
1379
+ !(
1380
+ isImmediateFunctionPrototypeMethodCall(
1381
+ node.parent,
1382
+ ) &&
1383
+ node.parent.callee === node &&
1384
+ IGNORE_FUNCTION_PROTOTYPE_METHODS
1385
+ );
1386
+
1387
+ if (
1388
+ nodeObjHasExcessParens &&
1389
+ precedence(node.object) >= precedence(node) &&
1390
+ (node.computed ||
1391
+ !(
1392
+ astUtils.isDecimalInteger(node.object) ||
1393
+ // RegExp literal is allowed to have parens (#1589)
1394
+ (node.object.type === "Literal" &&
1395
+ node.object.regex)
1396
+ ))
1397
+ ) {
1398
+ report(node.object);
1399
+ }
1400
+
1401
+ if (
1402
+ nodeObjHasExcessParens &&
1403
+ node.object.type === "CallExpression"
1404
+ ) {
1405
+ report(node.object);
1406
+ }
1407
+
1408
+ if (
1409
+ nodeObjHasExcessParens &&
1410
+ !IGNORE_NEW_IN_MEMBER_EXPR &&
1411
+ node.object.type === "NewExpression" &&
1412
+ isNewExpressionWithParens(node.object)
1413
+ ) {
1414
+ report(node.object);
1415
+ }
1416
+
1417
+ if (
1418
+ nodeObjHasExcessParens &&
1419
+ node.optional &&
1420
+ node.object.type === "ChainExpression"
1421
+ ) {
1422
+ report(node.object);
1423
+ }
1424
+
1425
+ if (node.computed && hasExcessParens(node.property)) {
1426
+ report(node.property);
1427
+ }
1428
+ },
1429
+
1430
+ "MethodDefinition[computed=true]"(node) {
1431
+ if (
1432
+ hasExcessParensWithPrecedence(
1433
+ node.key,
1434
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1435
+ )
1436
+ ) {
1437
+ report(node.key);
1438
+ }
1439
+ },
1440
+
1441
+ NewExpression: checkCallNew,
1442
+
1443
+ ObjectExpression(node) {
1444
+ node.properties
1445
+ .filter(
1446
+ property =>
1447
+ property.value &&
1448
+ hasExcessParensWithPrecedence(
1449
+ property.value,
1450
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1451
+ ),
1452
+ )
1453
+ .forEach(property => report(property.value));
1454
+ },
1455
+
1456
+ ObjectPattern(node) {
1457
+ node.properties
1458
+ .filter(property => {
1459
+ const value = property.value;
1460
+
1461
+ return (
1462
+ canBeAssignmentTarget(value) &&
1463
+ hasExcessParens(value)
1464
+ );
1465
+ })
1466
+ .forEach(property => report(property.value));
1467
+ },
1468
+
1469
+ Property(node) {
1470
+ if (node.computed) {
1471
+ const { key } = node;
1472
+
1473
+ if (
1474
+ key &&
1475
+ hasExcessParensWithPrecedence(
1476
+ key,
1477
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1478
+ )
1479
+ ) {
1480
+ report(key);
1481
+ }
1482
+ }
1483
+ },
1484
+
1485
+ PropertyDefinition(node) {
1486
+ if (
1487
+ node.computed &&
1488
+ hasExcessParensWithPrecedence(
1489
+ node.key,
1490
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1491
+ )
1492
+ ) {
1493
+ report(node.key);
1494
+ }
1495
+
1496
+ if (
1497
+ node.value &&
1498
+ hasExcessParensWithPrecedence(
1499
+ node.value,
1500
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1501
+ )
1502
+ ) {
1503
+ report(node.value);
1504
+ }
1505
+ },
1506
+
1507
+ RestElement(node) {
1508
+ const argument = node.argument;
1509
+
1510
+ if (
1511
+ canBeAssignmentTarget(argument) &&
1512
+ hasExcessParens(argument)
1513
+ ) {
1514
+ report(argument);
1515
+ }
1516
+ },
1517
+
1518
+ ReturnStatement(node) {
1519
+ const returnToken = sourceCode.getFirstToken(node);
1520
+
1521
+ if (isReturnAssignException(node)) {
1522
+ return;
1523
+ }
1524
+
1525
+ if (
1526
+ node.argument &&
1527
+ hasExcessParensNoLineTerminator(
1528
+ returnToken,
1529
+ node.argument,
1530
+ ) &&
1531
+ // RegExp literal is allowed to have parens (#1589)
1532
+ !(node.argument.type === "Literal" && node.argument.regex)
1533
+ ) {
1534
+ report(node.argument);
1535
+ }
1536
+ },
1537
+
1538
+ SequenceExpression(node) {
1539
+ const precedenceOfNode = precedence(node);
1540
+
1541
+ node.expressions
1542
+ .filter(e =>
1543
+ hasExcessParensWithPrecedence(e, precedenceOfNode),
1544
+ )
1545
+ .forEach(report);
1546
+ },
1547
+
1548
+ SwitchCase(node) {
1549
+ if (node.test && hasExcessParens(node.test)) {
1550
+ report(node.test);
1551
+ }
1552
+ },
1553
+
1554
+ SwitchStatement(node) {
1555
+ if (hasExcessParens(node.discriminant)) {
1556
+ report(node.discriminant);
1557
+ }
1558
+ },
1559
+
1560
+ ThrowStatement(node) {
1561
+ const throwToken = sourceCode.getFirstToken(node);
1562
+
1563
+ if (
1564
+ hasExcessParensNoLineTerminator(throwToken, node.argument)
1565
+ ) {
1566
+ report(node.argument);
1567
+ }
1568
+ },
1569
+
1570
+ UnaryExpression: checkArgumentWithPrecedence,
1571
+ UpdateExpression(node) {
1572
+ if (node.prefix) {
1573
+ checkArgumentWithPrecedence(node);
1574
+ } else {
1575
+ const { argument } = node;
1576
+ const operatorToken = sourceCode.getLastToken(node);
1577
+
1578
+ if (
1579
+ argument.loc.end.line === operatorToken.loc.start.line
1580
+ ) {
1581
+ checkArgumentWithPrecedence(node);
1582
+ } else {
1583
+ if (hasDoubleExcessParens(argument)) {
1584
+ report(argument);
1585
+ }
1586
+ }
1587
+ }
1588
+ },
1589
+ AwaitExpression: checkArgumentWithPrecedence,
1590
+
1591
+ VariableDeclarator(node) {
1592
+ if (
1593
+ node.init &&
1594
+ hasExcessParensWithPrecedence(
1595
+ node.init,
1596
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1597
+ ) &&
1598
+ // RegExp literal is allowed to have parens (#1589)
1599
+ !(node.init.type === "Literal" && node.init.regex)
1600
+ ) {
1601
+ report(node.init);
1602
+ }
1603
+ },
1604
+
1605
+ WhileStatement(node) {
1606
+ if (
1607
+ hasExcessParens(node.test) &&
1608
+ !isCondAssignException(node)
1609
+ ) {
1610
+ report(node.test);
1611
+ }
1612
+ },
1613
+
1614
+ WithStatement(node) {
1615
+ if (hasExcessParens(node.object)) {
1616
+ report(node.object);
1617
+ }
1618
+ },
1619
+
1620
+ YieldExpression(node) {
1621
+ if (node.argument) {
1622
+ const yieldToken = sourceCode.getFirstToken(node);
1623
+
1624
+ if (
1625
+ (precedence(node.argument) >= precedence(node) &&
1626
+ hasExcessParensNoLineTerminator(
1627
+ yieldToken,
1628
+ node.argument,
1629
+ )) ||
1630
+ hasDoubleExcessParens(node.argument)
1631
+ ) {
1632
+ report(node.argument);
1633
+ }
1634
+ }
1635
+ },
1636
+
1637
+ ClassDeclaration: checkClass,
1638
+ ClassExpression: checkClass,
1639
+
1640
+ SpreadElement: checkSpreadOperator,
1641
+ SpreadProperty: checkSpreadOperator,
1642
+ ExperimentalSpreadProperty: checkSpreadOperator,
1643
+
1644
+ TemplateLiteral(node) {
1645
+ node.expressions
1646
+ .filter(e => e && hasExcessParens(e))
1647
+ .forEach(report);
1648
+ },
1649
+
1650
+ AssignmentPattern(node) {
1651
+ const { left, right } = node;
1652
+
1653
+ if (canBeAssignmentTarget(left) && hasExcessParens(left)) {
1654
+ report(left);
1655
+ }
1656
+
1657
+ if (
1658
+ right &&
1659
+ hasExcessParensWithPrecedence(
1660
+ right,
1661
+ PRECEDENCE_OF_ASSIGNMENT_EXPR,
1662
+ )
1663
+ ) {
1664
+ report(right);
1665
+ }
1666
+ },
1667
+ };
1668
+ },
1340
1669
  };