eslint 8.57.1 → 9.39.1

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