eslint 9.22.0 → 9.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (417) hide show
  1. package/README.md +48 -46
  2. package/bin/eslint.js +92 -90
  3. package/conf/default-cli-options.js +22 -22
  4. package/conf/ecma-version.js +1 -1
  5. package/conf/globals.js +97 -98
  6. package/conf/replacements.json +24 -20
  7. package/conf/rule-type-list.json +88 -92
  8. package/lib/api.js +12 -12
  9. package/lib/cli-engine/cli-engine.js +830 -810
  10. package/lib/cli-engine/file-enumerator.js +381 -387
  11. package/lib/cli-engine/formatters/formatters-meta.json +16 -16
  12. package/lib/cli-engine/formatters/html.js +107 -99
  13. package/lib/cli-engine/formatters/json-with-metadata.js +5 -5
  14. package/lib/cli-engine/formatters/json.js +2 -2
  15. package/lib/cli-engine/formatters/stylish.js +96 -75
  16. package/lib/cli-engine/hash.js +1 -1
  17. package/lib/cli-engine/index.js +1 -1
  18. package/lib/cli-engine/lint-result-cache.js +144 -145
  19. package/lib/cli-engine/load-rules.js +16 -16
  20. package/lib/cli.js +638 -457
  21. package/lib/config/config-loader.js +726 -622
  22. package/lib/config/config.js +247 -221
  23. package/lib/config/default-config.js +54 -45
  24. package/lib/config/flat-config-array.js +167 -172
  25. package/lib/config/flat-config-helpers.js +72 -72
  26. package/lib/config/flat-config-schema.js +375 -368
  27. package/lib/config/rule-validator.js +139 -144
  28. package/lib/config-api.js +2 -2
  29. package/lib/eslint/eslint-helpers.js +756 -681
  30. package/lib/eslint/eslint.js +934 -912
  31. package/lib/eslint/index.js +2 -2
  32. package/lib/eslint/legacy-eslint.js +577 -533
  33. package/lib/languages/js/index.js +263 -264
  34. package/lib/languages/js/source-code/index.js +1 -1
  35. package/lib/languages/js/source-code/source-code.js +1128 -1057
  36. package/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js +39 -35
  37. package/lib/languages/js/source-code/token-store/backward-token-cursor.js +35 -36
  38. package/lib/languages/js/source-code/token-store/cursor.js +36 -36
  39. package/lib/languages/js/source-code/token-store/cursors.js +80 -52
  40. package/lib/languages/js/source-code/token-store/decorative-cursor.js +17 -18
  41. package/lib/languages/js/source-code/token-store/filter-cursor.js +19 -20
  42. package/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js +40 -32
  43. package/lib/languages/js/source-code/token-store/forward-token-cursor.js +40 -41
  44. package/lib/languages/js/source-code/token-store/index.js +592 -498
  45. package/lib/languages/js/source-code/token-store/limit-cursor.js +17 -18
  46. package/lib/languages/js/source-code/token-store/padded-token-cursor.js +23 -16
  47. package/lib/languages/js/source-code/token-store/skip-cursor.js +19 -20
  48. package/lib/languages/js/source-code/token-store/utils.js +63 -60
  49. package/lib/languages/js/validate-language-options.js +104 -89
  50. package/lib/linter/apply-disable-directives.js +467 -383
  51. package/lib/linter/code-path-analysis/code-path-analyzer.js +650 -672
  52. package/lib/linter/code-path-analysis/code-path-segment.js +215 -216
  53. package/lib/linter/code-path-analysis/code-path-state.js +2118 -2096
  54. package/lib/linter/code-path-analysis/code-path.js +307 -319
  55. package/lib/linter/code-path-analysis/debug-helpers.js +183 -163
  56. package/lib/linter/code-path-analysis/fork-context.js +296 -271
  57. package/lib/linter/code-path-analysis/id-generator.js +22 -23
  58. package/lib/linter/file-context.js +119 -120
  59. package/lib/linter/index.js +3 -3
  60. package/lib/linter/interpolate.js +16 -16
  61. package/lib/linter/linter.js +2403 -2045
  62. package/lib/linter/node-event-generator.js +284 -225
  63. package/lib/linter/report-translator.js +256 -219
  64. package/lib/linter/rule-fixer.js +122 -124
  65. package/lib/linter/rules.js +36 -36
  66. package/lib/linter/safe-emitter.js +18 -18
  67. package/lib/linter/source-code-fixer.js +94 -92
  68. package/lib/linter/timing.js +104 -101
  69. package/lib/linter/vfile.js +70 -73
  70. package/lib/options.js +404 -361
  71. package/lib/rule-tester/index.js +1 -1
  72. package/lib/rule-tester/rule-tester.js +1308 -1046
  73. package/lib/rules/accessor-pairs.js +298 -263
  74. package/lib/rules/array-bracket-newline.js +250 -238
  75. package/lib/rules/array-bracket-spacing.js +263 -224
  76. package/lib/rules/array-callback-return.js +402 -356
  77. package/lib/rules/array-element-newline.js +358 -313
  78. package/lib/rules/arrow-body-style.js +400 -281
  79. package/lib/rules/arrow-parens.js +206 -173
  80. package/lib/rules/arrow-spacing.js +169 -163
  81. package/lib/rules/block-scoped-var.js +125 -123
  82. package/lib/rules/block-spacing.js +186 -176
  83. package/lib/rules/brace-style.js +262 -199
  84. package/lib/rules/callback-return.js +203 -190
  85. package/lib/rules/camelcase.js +403 -392
  86. package/lib/rules/capitalized-comments.js +253 -232
  87. package/lib/rules/class-methods-use-this.js +224 -172
  88. package/lib/rules/comma-dangle.js +379 -346
  89. package/lib/rules/comma-spacing.js +193 -195
  90. package/lib/rules/comma-style.js +375 -316
  91. package/lib/rules/complexity.js +173 -169
  92. package/lib/rules/computed-property-spacing.js +236 -211
  93. package/lib/rules/consistent-return.js +181 -170
  94. package/lib/rules/consistent-this.js +167 -147
  95. package/lib/rules/constructor-super.js +412 -404
  96. package/lib/rules/curly.js +407 -332
  97. package/lib/rules/default-case-last.js +38 -31
  98. package/lib/rules/default-case.js +89 -85
  99. package/lib/rules/default-param-last.js +69 -54
  100. package/lib/rules/dot-location.js +122 -110
  101. package/lib/rules/dot-notation.js +192 -156
  102. package/lib/rules/eol-last.js +122 -120
  103. package/lib/rules/eqeqeq.js +168 -155
  104. package/lib/rules/for-direction.js +146 -121
  105. package/lib/rules/func-call-spacing.js +261 -231
  106. package/lib/rules/func-name-matching.js +293 -209
  107. package/lib/rules/func-names.js +165 -164
  108. package/lib/rules/func-style.js +159 -127
  109. package/lib/rules/function-call-argument-newline.js +152 -129
  110. package/lib/rules/function-paren-newline.js +349 -291
  111. package/lib/rules/generator-star-spacing.js +229 -210
  112. package/lib/rules/getter-return.js +208 -172
  113. package/lib/rules/global-require.js +85 -74
  114. package/lib/rules/grouped-accessor-pairs.js +170 -150
  115. package/lib/rules/guard-for-in.js +72 -63
  116. package/lib/rules/handle-callback-err.js +108 -103
  117. package/lib/rules/id-blacklist.js +182 -199
  118. package/lib/rules/id-denylist.js +168 -187
  119. package/lib/rules/id-length.js +197 -171
  120. package/lib/rules/id-match.js +344 -289
  121. package/lib/rules/implicit-arrow-linebreak.js +102 -79
  122. package/lib/rules/indent-legacy.js +1344 -1118
  123. package/lib/rules/indent.js +2272 -1759
  124. package/lib/rules/index.js +317 -292
  125. package/lib/rules/init-declarations.js +137 -107
  126. package/lib/rules/jsx-quotes.js +94 -82
  127. package/lib/rules/key-spacing.js +750 -633
  128. package/lib/rules/keyword-spacing.js +648 -605
  129. package/lib/rules/line-comment-position.js +142 -128
  130. package/lib/rules/linebreak-style.js +107 -106
  131. package/lib/rules/lines-around-comment.js +540 -448
  132. package/lib/rules/lines-around-directive.js +233 -203
  133. package/lib/rules/lines-between-class-members.js +305 -234
  134. package/lib/rules/logical-assignment-operators.js +582 -399
  135. package/lib/rules/max-classes-per-file.js +69 -68
  136. package/lib/rules/max-depth.js +146 -143
  137. package/lib/rules/max-len.js +473 -434
  138. package/lib/rules/max-lines-per-function.js +201 -176
  139. package/lib/rules/max-lines.js +158 -162
  140. package/lib/rules/max-nested-callbacks.js +102 -104
  141. package/lib/rules/max-params.js +78 -76
  142. package/lib/rules/max-statements-per-line.js +205 -198
  143. package/lib/rules/max-statements.js +168 -164
  144. package/lib/rules/multiline-comment-style.js +637 -479
  145. package/lib/rules/multiline-ternary.js +241 -176
  146. package/lib/rules/new-cap.js +233 -213
  147. package/lib/rules/new-parens.js +88 -79
  148. package/lib/rules/newline-after-var.js +287 -250
  149. package/lib/rules/newline-before-return.js +229 -222
  150. package/lib/rules/newline-per-chained-call.js +142 -127
  151. package/lib/rules/no-alert.js +90 -79
  152. package/lib/rules/no-array-constructor.js +125 -113
  153. package/lib/rules/no-async-promise-executor.js +30 -24
  154. package/lib/rules/no-await-in-loop.js +69 -71
  155. package/lib/rules/no-bitwise.js +124 -100
  156. package/lib/rules/no-buffer-constructor.js +55 -47
  157. package/lib/rules/no-caller.js +39 -33
  158. package/lib/rules/no-case-declarations.js +61 -57
  159. package/lib/rules/no-catch-shadow.js +76 -73
  160. package/lib/rules/no-class-assign.js +51 -48
  161. package/lib/rules/no-compare-neg-zero.js +62 -48
  162. package/lib/rules/no-cond-assign.js +148 -132
  163. package/lib/rules/no-confusing-arrow.js +98 -81
  164. package/lib/rules/no-console.js +202 -199
  165. package/lib/rules/no-const-assign.js +47 -41
  166. package/lib/rules/no-constant-binary-expression.js +500 -405
  167. package/lib/rules/no-constant-condition.js +158 -143
  168. package/lib/rules/no-constructor-return.js +49 -49
  169. package/lib/rules/no-continue.js +25 -27
  170. package/lib/rules/no-control-regex.js +125 -121
  171. package/lib/rules/no-debugger.js +28 -30
  172. package/lib/rules/no-delete-var.js +29 -29
  173. package/lib/rules/no-div-regex.js +47 -41
  174. package/lib/rules/no-dupe-args.js +68 -69
  175. package/lib/rules/no-dupe-class-members.js +102 -89
  176. package/lib/rules/no-dupe-else-if.js +100 -77
  177. package/lib/rules/no-dupe-keys.js +133 -110
  178. package/lib/rules/no-duplicate-case.js +50 -43
  179. package/lib/rules/no-duplicate-imports.js +179 -176
  180. package/lib/rules/no-else-return.js +430 -385
  181. package/lib/rules/no-empty-character-class.js +57 -50
  182. package/lib/rules/no-empty-function.js +127 -128
  183. package/lib/rules/no-empty-pattern.js +63 -58
  184. package/lib/rules/no-empty-static-block.js +37 -35
  185. package/lib/rules/no-empty.js +98 -86
  186. package/lib/rules/no-eq-null.js +37 -32
  187. package/lib/rules/no-eval.js +256 -250
  188. package/lib/rules/no-ex-assign.js +42 -39
  189. package/lib/rules/no-extend-native.js +161 -159
  190. package/lib/rules/no-extra-bind.js +201 -190
  191. package/lib/rules/no-extra-boolean-cast.js +398 -348
  192. package/lib/rules/no-extra-label.js +150 -131
  193. package/lib/rules/no-extra-parens.js +1654 -1325
  194. package/lib/rules/no-extra-semi.js +146 -144
  195. package/lib/rules/no-fallthrough.js +199 -157
  196. package/lib/rules/no-floating-decimal.js +74 -66
  197. package/lib/rules/no-func-assign.js +54 -55
  198. package/lib/rules/no-global-assign.js +78 -73
  199. package/lib/rules/no-implicit-coercion.js +349 -293
  200. package/lib/rules/no-implicit-globals.js +158 -135
  201. package/lib/rules/no-implied-eval.js +140 -112
  202. package/lib/rules/no-import-assign.js +145 -159
  203. package/lib/rules/no-inline-comments.js +101 -95
  204. package/lib/rules/no-inner-declarations.js +115 -101
  205. package/lib/rules/no-invalid-regexp.js +222 -190
  206. package/lib/rules/no-invalid-this.js +123 -117
  207. package/lib/rules/no-irregular-whitespace.js +266 -252
  208. package/lib/rules/no-iterator.js +29 -33
  209. package/lib/rules/no-label-var.js +59 -62
  210. package/lib/rules/no-labels.js +138 -133
  211. package/lib/rules/no-lone-blocks.js +127 -123
  212. package/lib/rules/no-lonely-if.js +108 -77
  213. package/lib/rules/no-loop-func.js +238 -213
  214. package/lib/rules/no-loss-of-precision.js +218 -201
  215. package/lib/rules/no-magic-numbers.js +246 -218
  216. package/lib/rules/no-misleading-character-class.js +499 -446
  217. package/lib/rules/no-mixed-operators.js +188 -182
  218. package/lib/rules/no-mixed-requires.js +253 -240
  219. package/lib/rules/no-mixed-spaces-and-tabs.js +134 -121
  220. package/lib/rules/no-multi-assign.js +46 -44
  221. package/lib/rules/no-multi-spaces.js +163 -143
  222. package/lib/rules/no-multi-str.js +42 -41
  223. package/lib/rules/no-multiple-empty-lines.js +196 -158
  224. package/lib/rules/no-native-reassign.js +90 -85
  225. package/lib/rules/no-negated-condition.js +79 -75
  226. package/lib/rules/no-negated-in-lhs.js +45 -43
  227. package/lib/rules/no-nested-ternary.js +33 -32
  228. package/lib/rules/no-new-func.js +71 -62
  229. package/lib/rules/no-new-native-nonconstructor.js +43 -39
  230. package/lib/rules/no-new-object.js +48 -48
  231. package/lib/rules/no-new-require.js +48 -47
  232. package/lib/rules/no-new-symbol.js +52 -50
  233. package/lib/rules/no-new-wrappers.js +43 -41
  234. package/lib/rules/no-new.js +28 -29
  235. package/lib/rules/no-nonoctal-decimal-escape.js +141 -121
  236. package/lib/rules/no-obj-calls.js +66 -53
  237. package/lib/rules/no-object-constructor.js +104 -97
  238. package/lib/rules/no-octal-escape.js +40 -43
  239. package/lib/rules/no-octal.js +32 -32
  240. package/lib/rules/no-param-reassign.js +235 -217
  241. package/lib/rules/no-path-concat.js +66 -67
  242. package/lib/rules/no-plusplus.js +60 -61
  243. package/lib/rules/no-process-env.js +49 -48
  244. package/lib/rules/no-process-exit.js +54 -50
  245. package/lib/rules/no-promise-executor-return.js +214 -182
  246. package/lib/rules/no-proto.js +26 -29
  247. package/lib/rules/no-prototype-builtins.js +146 -124
  248. package/lib/rules/no-redeclare.js +154 -152
  249. package/lib/rules/no-regex-spaces.js +183 -161
  250. package/lib/rules/no-restricted-exports.js +208 -185
  251. package/lib/rules/no-restricted-globals.js +111 -112
  252. package/lib/rules/no-restricted-imports.js +657 -537
  253. package/lib/rules/no-restricted-modules.js +222 -202
  254. package/lib/rules/no-restricted-properties.js +181 -153
  255. package/lib/rules/no-restricted-syntax.js +56 -52
  256. package/lib/rules/no-return-assign.js +55 -50
  257. package/lib/rules/no-return-await.js +148 -124
  258. package/lib/rules/no-script-url.js +52 -45
  259. package/lib/rules/no-self-assign.js +148 -146
  260. package/lib/rules/no-self-compare.js +63 -46
  261. package/lib/rules/no-sequences.js +135 -116
  262. package/lib/rules/no-setter-return.js +185 -152
  263. package/lib/rules/no-shadow-restricted-names.js +61 -46
  264. package/lib/rules/no-shadow.js +342 -316
  265. package/lib/rules/no-spaced-func.js +82 -77
  266. package/lib/rules/no-sparse-arrays.js +54 -59
  267. package/lib/rules/no-sync.js +61 -60
  268. package/lib/rules/no-tabs.js +83 -72
  269. package/lib/rules/no-template-curly-in-string.js +33 -32
  270. package/lib/rules/no-ternary.js +25 -29
  271. package/lib/rules/no-this-before-super.js +321 -319
  272. package/lib/rules/no-throw-literal.js +31 -36
  273. package/lib/rules/no-trailing-spaces.js +199 -191
  274. package/lib/rules/no-undef-init.js +76 -61
  275. package/lib/rules/no-undef.js +51 -48
  276. package/lib/rules/no-undefined.js +73 -75
  277. package/lib/rules/no-underscore-dangle.js +370 -327
  278. package/lib/rules/no-unexpected-multiline.js +112 -102
  279. package/lib/rules/no-unmodified-loop-condition.js +254 -254
  280. package/lib/rules/no-unneeded-ternary.js +212 -147
  281. package/lib/rules/no-unreachable-loop.js +145 -142
  282. package/lib/rules/no-unreachable.js +255 -248
  283. package/lib/rules/no-unsafe-finally.js +93 -85
  284. package/lib/rules/no-unsafe-negation.js +105 -83
  285. package/lib/rules/no-unsafe-optional-chaining.js +192 -178
  286. package/lib/rules/no-unused-expressions.js +178 -162
  287. package/lib/rules/no-unused-labels.js +139 -124
  288. package/lib/rules/no-unused-private-class-members.js +206 -182
  289. package/lib/rules/no-unused-vars.js +1669 -1449
  290. package/lib/rules/no-use-before-define.js +229 -231
  291. package/lib/rules/no-useless-assignment.js +590 -511
  292. package/lib/rules/no-useless-backreference.js +212 -193
  293. package/lib/rules/no-useless-call.js +58 -53
  294. package/lib/rules/no-useless-catch.js +40 -40
  295. package/lib/rules/no-useless-computed-key.js +144 -115
  296. package/lib/rules/no-useless-concat.js +65 -60
  297. package/lib/rules/no-useless-constructor.js +158 -111
  298. package/lib/rules/no-useless-escape.js +342 -291
  299. package/lib/rules/no-useless-rename.js +183 -156
  300. package/lib/rules/no-useless-return.js +344 -312
  301. package/lib/rules/no-var.js +233 -212
  302. package/lib/rules/no-void.js +50 -48
  303. package/lib/rules/no-warning-comments.js +191 -186
  304. package/lib/rules/no-whitespace-before-property.js +131 -115
  305. package/lib/rules/no-with.js +24 -26
  306. package/lib/rules/nonblock-statement-body-position.js +149 -130
  307. package/lib/rules/object-curly-newline.js +306 -265
  308. package/lib/rules/object-curly-spacing.js +360 -314
  309. package/lib/rules/object-property-newline.js +137 -106
  310. package/lib/rules/object-shorthand.js +607 -502
  311. package/lib/rules/one-var-declaration-per-line.js +104 -100
  312. package/lib/rules/one-var.js +653 -537
  313. package/lib/rules/operator-assignment.js +219 -161
  314. package/lib/rules/operator-linebreak.js +295 -251
  315. package/lib/rules/padded-blocks.js +346 -308
  316. package/lib/rules/padding-line-between-statements.js +443 -439
  317. package/lib/rules/prefer-arrow-callback.js +362 -313
  318. package/lib/rules/prefer-const.js +418 -377
  319. package/lib/rules/prefer-destructuring.js +301 -279
  320. package/lib/rules/prefer-exponentiation-operator.js +176 -133
  321. package/lib/rules/prefer-named-capture-group.js +153 -140
  322. package/lib/rules/prefer-numeric-literals.js +121 -113
  323. package/lib/rules/prefer-object-has-own.js +116 -82
  324. package/lib/rules/prefer-object-spread.js +213 -193
  325. package/lib/rules/prefer-promise-reject-errors.js +140 -122
  326. package/lib/rules/prefer-reflect.js +127 -107
  327. package/lib/rules/prefer-regex-literals.js +578 -466
  328. package/lib/rules/prefer-rest-params.js +79 -80
  329. package/lib/rules/prefer-spread.js +47 -44
  330. package/lib/rules/prefer-template.js +266 -195
  331. package/lib/rules/quote-props.js +373 -307
  332. package/lib/rules/quotes.js +374 -326
  333. package/lib/rules/radix.js +152 -136
  334. package/lib/rules/require-atomic-updates.js +316 -285
  335. package/lib/rules/require-await.js +144 -116
  336. package/lib/rules/require-unicode-regexp.js +282 -177
  337. package/lib/rules/require-yield.js +53 -54
  338. package/lib/rules/rest-spread-spacing.js +128 -116
  339. package/lib/rules/semi-spacing.js +281 -250
  340. package/lib/rules/semi-style.js +176 -134
  341. package/lib/rules/semi.js +456 -436
  342. package/lib/rules/sort-imports.js +306 -233
  343. package/lib/rules/sort-keys.js +219 -188
  344. package/lib/rules/sort-vars.js +127 -93
  345. package/lib/rules/space-before-blocks.js +199 -189
  346. package/lib/rules/space-before-function-paren.js +186 -166
  347. package/lib/rules/space-in-parens.js +359 -288
  348. package/lib/rules/space-infix-ops.js +237 -201
  349. package/lib/rules/space-unary-ops.js +356 -298
  350. package/lib/rules/spaced-comment.js +363 -319
  351. package/lib/rules/strict.js +265 -230
  352. package/lib/rules/switch-colon-spacing.js +130 -122
  353. package/lib/rules/symbol-description.js +45 -48
  354. package/lib/rules/template-curly-spacing.js +148 -142
  355. package/lib/rules/template-tag-spacing.js +98 -88
  356. package/lib/rules/unicode-bom.js +54 -56
  357. package/lib/rules/use-isnan.js +237 -206
  358. package/lib/rules/utils/ast-utils.js +2039 -1860
  359. package/lib/rules/utils/char-source.js +162 -155
  360. package/lib/rules/utils/fix-tracker.js +83 -80
  361. package/lib/rules/utils/keywords.js +59 -59
  362. package/lib/rules/utils/lazy-loading-rule-map.js +79 -76
  363. package/lib/rules/utils/regular-expressions.js +32 -24
  364. package/lib/rules/utils/unicode/index.js +4 -4
  365. package/lib/rules/utils/unicode/is-combining-character.js +1 -1
  366. package/lib/rules/utils/unicode/is-emoji-modifier.js +1 -1
  367. package/lib/rules/utils/unicode/is-regional-indicator-symbol.js +1 -1
  368. package/lib/rules/utils/unicode/is-surrogate-pair.js +1 -1
  369. package/lib/rules/valid-typeof.js +153 -111
  370. package/lib/rules/vars-on-top.js +152 -145
  371. package/lib/rules/wrap-iife.js +204 -191
  372. package/lib/rules/wrap-regex.js +70 -58
  373. package/lib/rules/yield-star-spacing.js +145 -134
  374. package/lib/rules/yoda.js +283 -272
  375. package/lib/services/parser-service.js +35 -35
  376. package/lib/services/processor-service.js +66 -73
  377. package/lib/services/suppressions-service.js +289 -0
  378. package/lib/shared/ajv.js +14 -14
  379. package/lib/shared/assert.js +3 -4
  380. package/lib/shared/ast-utils.js +7 -6
  381. package/lib/shared/deep-merge-arrays.js +24 -22
  382. package/lib/shared/directives.js +3 -2
  383. package/lib/shared/flags.js +50 -17
  384. package/lib/shared/logging.js +24 -25
  385. package/lib/shared/option-utils.js +43 -36
  386. package/lib/shared/runtime-info.js +136 -127
  387. package/lib/shared/serialization.js +27 -27
  388. package/lib/shared/severity.js +22 -22
  389. package/lib/shared/stats.js +5 -5
  390. package/lib/shared/string-utils.js +16 -16
  391. package/lib/shared/text-table.js +28 -27
  392. package/lib/shared/traverser.js +153 -146
  393. package/lib/shared/types.js +4 -27
  394. package/lib/types/index.d.ts +2010 -1559
  395. package/lib/types/rules.d.ts +5253 -5140
  396. package/lib/types/use-at-your-own-risk.d.ts +32 -30
  397. package/lib/unsupported-api.js +5 -5
  398. package/messages/all-files-ignored.js +3 -3
  399. package/messages/all-matched-files-ignored.js +3 -3
  400. package/messages/config-file-missing.js +2 -2
  401. package/messages/config-plugin-missing.js +3 -3
  402. package/messages/config-serialize-function.js +9 -7
  403. package/messages/eslintrc-incompat.js +13 -15
  404. package/messages/eslintrc-plugins.js +3 -4
  405. package/messages/extend-config-missing.js +3 -3
  406. package/messages/failed-to-read-json.js +3 -3
  407. package/messages/file-not-found.js +3 -3
  408. package/messages/invalid-rule-options.js +2 -2
  409. package/messages/invalid-rule-severity.js +2 -2
  410. package/messages/no-config-found.js +3 -3
  411. package/messages/plugin-conflict.js +8 -8
  412. package/messages/plugin-invalid.js +3 -3
  413. package/messages/plugin-missing.js +3 -3
  414. package/messages/print-config-with-directory-path.js +2 -2
  415. package/messages/shared.js +6 -1
  416. package/messages/whitespace-found.js +3 -3
  417. package/package.json +14 -20
@@ -20,93 +20,93 @@ const astUtils = require("./utils/ast-utils");
20
20
  //------------------------------------------------------------------------------
21
21
 
22
22
  const KNOWN_NODES = new Set([
23
- "AssignmentExpression",
24
- "AssignmentPattern",
25
- "ArrayExpression",
26
- "ArrayPattern",
27
- "ArrowFunctionExpression",
28
- "AwaitExpression",
29
- "BlockStatement",
30
- "BinaryExpression",
31
- "BreakStatement",
32
- "CallExpression",
33
- "CatchClause",
34
- "ChainExpression",
35
- "ClassBody",
36
- "ClassDeclaration",
37
- "ClassExpression",
38
- "ConditionalExpression",
39
- "ContinueStatement",
40
- "DoWhileStatement",
41
- "DebuggerStatement",
42
- "EmptyStatement",
43
- "ExperimentalRestProperty",
44
- "ExperimentalSpreadProperty",
45
- "ExpressionStatement",
46
- "ForStatement",
47
- "ForInStatement",
48
- "ForOfStatement",
49
- "FunctionDeclaration",
50
- "FunctionExpression",
51
- "Identifier",
52
- "IfStatement",
53
- "Literal",
54
- "LabeledStatement",
55
- "LogicalExpression",
56
- "MemberExpression",
57
- "MetaProperty",
58
- "MethodDefinition",
59
- "NewExpression",
60
- "ObjectExpression",
61
- "ObjectPattern",
62
- "PrivateIdentifier",
63
- "Program",
64
- "Property",
65
- "PropertyDefinition",
66
- "RestElement",
67
- "ReturnStatement",
68
- "SequenceExpression",
69
- "SpreadElement",
70
- "StaticBlock",
71
- "Super",
72
- "SwitchCase",
73
- "SwitchStatement",
74
- "TaggedTemplateExpression",
75
- "TemplateElement",
76
- "TemplateLiteral",
77
- "ThisExpression",
78
- "ThrowStatement",
79
- "TryStatement",
80
- "UnaryExpression",
81
- "UpdateExpression",
82
- "VariableDeclaration",
83
- "VariableDeclarator",
84
- "WhileStatement",
85
- "WithStatement",
86
- "YieldExpression",
87
- "JSXFragment",
88
- "JSXOpeningFragment",
89
- "JSXClosingFragment",
90
- "JSXIdentifier",
91
- "JSXNamespacedName",
92
- "JSXMemberExpression",
93
- "JSXEmptyExpression",
94
- "JSXExpressionContainer",
95
- "JSXElement",
96
- "JSXClosingElement",
97
- "JSXOpeningElement",
98
- "JSXAttribute",
99
- "JSXSpreadAttribute",
100
- "JSXText",
101
- "ExportDefaultDeclaration",
102
- "ExportNamedDeclaration",
103
- "ExportAllDeclaration",
104
- "ExportSpecifier",
105
- "ImportDeclaration",
106
- "ImportSpecifier",
107
- "ImportDefaultSpecifier",
108
- "ImportNamespaceSpecifier",
109
- "ImportExpression"
23
+ "AssignmentExpression",
24
+ "AssignmentPattern",
25
+ "ArrayExpression",
26
+ "ArrayPattern",
27
+ "ArrowFunctionExpression",
28
+ "AwaitExpression",
29
+ "BlockStatement",
30
+ "BinaryExpression",
31
+ "BreakStatement",
32
+ "CallExpression",
33
+ "CatchClause",
34
+ "ChainExpression",
35
+ "ClassBody",
36
+ "ClassDeclaration",
37
+ "ClassExpression",
38
+ "ConditionalExpression",
39
+ "ContinueStatement",
40
+ "DoWhileStatement",
41
+ "DebuggerStatement",
42
+ "EmptyStatement",
43
+ "ExperimentalRestProperty",
44
+ "ExperimentalSpreadProperty",
45
+ "ExpressionStatement",
46
+ "ForStatement",
47
+ "ForInStatement",
48
+ "ForOfStatement",
49
+ "FunctionDeclaration",
50
+ "FunctionExpression",
51
+ "Identifier",
52
+ "IfStatement",
53
+ "Literal",
54
+ "LabeledStatement",
55
+ "LogicalExpression",
56
+ "MemberExpression",
57
+ "MetaProperty",
58
+ "MethodDefinition",
59
+ "NewExpression",
60
+ "ObjectExpression",
61
+ "ObjectPattern",
62
+ "PrivateIdentifier",
63
+ "Program",
64
+ "Property",
65
+ "PropertyDefinition",
66
+ "RestElement",
67
+ "ReturnStatement",
68
+ "SequenceExpression",
69
+ "SpreadElement",
70
+ "StaticBlock",
71
+ "Super",
72
+ "SwitchCase",
73
+ "SwitchStatement",
74
+ "TaggedTemplateExpression",
75
+ "TemplateElement",
76
+ "TemplateLiteral",
77
+ "ThisExpression",
78
+ "ThrowStatement",
79
+ "TryStatement",
80
+ "UnaryExpression",
81
+ "UpdateExpression",
82
+ "VariableDeclaration",
83
+ "VariableDeclarator",
84
+ "WhileStatement",
85
+ "WithStatement",
86
+ "YieldExpression",
87
+ "JSXFragment",
88
+ "JSXOpeningFragment",
89
+ "JSXClosingFragment",
90
+ "JSXIdentifier",
91
+ "JSXNamespacedName",
92
+ "JSXMemberExpression",
93
+ "JSXEmptyExpression",
94
+ "JSXExpressionContainer",
95
+ "JSXElement",
96
+ "JSXClosingElement",
97
+ "JSXOpeningElement",
98
+ "JSXAttribute",
99
+ "JSXSpreadAttribute",
100
+ "JSXText",
101
+ "ExportDefaultDeclaration",
102
+ "ExportNamedDeclaration",
103
+ "ExportAllDeclaration",
104
+ "ExportSpecifier",
105
+ "ImportDeclaration",
106
+ "ImportSpecifier",
107
+ "ImportDefaultSpecifier",
108
+ "ImportNamespaceSpecifier",
109
+ "ImportExpression",
110
110
  ]);
111
111
 
112
112
  /*
@@ -122,1700 +122,2213 @@ const KNOWN_NODES = new Set([
122
122
  * and report the token if the two values are not equal.
123
123
  */
124
124
 
125
-
126
125
  /**
127
126
  * A mutable map that stores (key, value) pairs. The keys are numeric indices, and must be unique.
128
127
  * This is intended to be a generic wrapper around a map with non-negative integer keys, so that the underlying implementation
129
128
  * can easily be swapped out.
130
129
  */
131
130
  class IndexMap {
132
-
133
- /**
134
- * Creates an empty map
135
- * @param {number} maxKey The maximum key
136
- */
137
- constructor(maxKey) {
138
-
139
- // Initializing the array with the maximum expected size avoids dynamic reallocations that could degrade performance.
140
- this._values = Array(maxKey + 1);
141
- }
142
-
143
- /**
144
- * Inserts an entry into the map.
145
- * @param {number} key The entry's key
146
- * @param {any} value The entry's value
147
- * @returns {void}
148
- */
149
- insert(key, value) {
150
- this._values[key] = value;
151
- }
152
-
153
- /**
154
- * Finds the value of the entry with the largest key less than or equal to the provided key
155
- * @param {number} key The provided key
156
- * @returns {*|undefined} The value of the found entry, or undefined if no such entry exists.
157
- */
158
- findLastNotAfter(key) {
159
- const values = this._values;
160
-
161
- for (let index = key; index >= 0; index--) {
162
- const value = values[index];
163
-
164
- if (value) {
165
- return value;
166
- }
167
- }
168
- return void 0;
169
- }
170
-
171
- /**
172
- * Deletes all of the keys in the interval [start, end)
173
- * @param {number} start The start of the range
174
- * @param {number} end The end of the range
175
- * @returns {void}
176
- */
177
- deleteRange(start, end) {
178
- this._values.fill(void 0, start, end);
179
- }
131
+ /**
132
+ * Creates an empty map
133
+ * @param {number} maxKey The maximum key
134
+ */
135
+ constructor(maxKey) {
136
+ // Initializing the array with the maximum expected size avoids dynamic reallocations that could degrade performance.
137
+ this._values = Array(maxKey + 1);
138
+ }
139
+
140
+ /**
141
+ * Inserts an entry into the map.
142
+ * @param {number} key The entry's key
143
+ * @param {any} value The entry's value
144
+ * @returns {void}
145
+ */
146
+ insert(key, value) {
147
+ this._values[key] = value;
148
+ }
149
+
150
+ /**
151
+ * Finds the value of the entry with the largest key less than or equal to the provided key
152
+ * @param {number} key The provided key
153
+ * @returns {*|undefined} The value of the found entry, or undefined if no such entry exists.
154
+ */
155
+ findLastNotAfter(key) {
156
+ const values = this._values;
157
+
158
+ for (let index = key; index >= 0; index--) {
159
+ const value = values[index];
160
+
161
+ if (value) {
162
+ return value;
163
+ }
164
+ }
165
+ return void 0;
166
+ }
167
+
168
+ /**
169
+ * Deletes all of the keys in the interval [start, end)
170
+ * @param {number} start The start of the range
171
+ * @param {number} end The end of the range
172
+ * @returns {void}
173
+ */
174
+ deleteRange(start, end) {
175
+ this._values.fill(void 0, start, end);
176
+ }
180
177
  }
181
178
 
182
179
  /**
183
180
  * A helper class to get token-based info related to indentation
184
181
  */
185
182
  class TokenInfo {
186
-
187
- /**
188
- * @param {SourceCode} sourceCode A SourceCode object
189
- */
190
- constructor(sourceCode) {
191
- this.sourceCode = sourceCode;
192
- this.firstTokensByLineNumber = new Map();
193
- const tokens = sourceCode.tokensAndComments;
194
-
195
- for (let i = 0; i < tokens.length; i++) {
196
- const token = tokens[i];
197
-
198
- if (!this.firstTokensByLineNumber.has(token.loc.start.line)) {
199
- this.firstTokensByLineNumber.set(token.loc.start.line, token);
200
- }
201
- if (!this.firstTokensByLineNumber.has(token.loc.end.line) && sourceCode.text.slice(token.range[1] - token.loc.end.column, token.range[1]).trim()) {
202
- this.firstTokensByLineNumber.set(token.loc.end.line, token);
203
- }
204
- }
205
- }
206
-
207
- /**
208
- * Gets the first token on a given token's line
209
- * @param {Token|ASTNode} token a node or token
210
- * @returns {Token} The first token on the given line
211
- */
212
- getFirstTokenOfLine(token) {
213
- return this.firstTokensByLineNumber.get(token.loc.start.line);
214
- }
215
-
216
- /**
217
- * Determines whether a token is the first token in its line
218
- * @param {Token} token The token
219
- * @returns {boolean} `true` if the token is the first on its line
220
- */
221
- isFirstTokenOfLine(token) {
222
- return this.getFirstTokenOfLine(token) === token;
223
- }
224
-
225
- /**
226
- * Get the actual indent of a token
227
- * @param {Token} token Token to examine. This should be the first token on its line.
228
- * @returns {string} The indentation characters that precede the token
229
- */
230
- getTokenIndent(token) {
231
- return this.sourceCode.text.slice(token.range[0] - token.loc.start.column, token.range[0]);
232
- }
183
+ /**
184
+ * @param {SourceCode} sourceCode A SourceCode object
185
+ */
186
+ constructor(sourceCode) {
187
+ this.sourceCode = sourceCode;
188
+ this.firstTokensByLineNumber = new Map();
189
+ const tokens = sourceCode.tokensAndComments;
190
+
191
+ for (let i = 0; i < tokens.length; i++) {
192
+ const token = tokens[i];
193
+
194
+ if (!this.firstTokensByLineNumber.has(token.loc.start.line)) {
195
+ this.firstTokensByLineNumber.set(token.loc.start.line, token);
196
+ }
197
+ if (
198
+ !this.firstTokensByLineNumber.has(token.loc.end.line) &&
199
+ sourceCode.text
200
+ .slice(
201
+ token.range[1] - token.loc.end.column,
202
+ token.range[1],
203
+ )
204
+ .trim()
205
+ ) {
206
+ this.firstTokensByLineNumber.set(token.loc.end.line, token);
207
+ }
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Gets the first token on a given token's line
213
+ * @param {Token|ASTNode} token a node or token
214
+ * @returns {Token} The first token on the given line
215
+ */
216
+ getFirstTokenOfLine(token) {
217
+ return this.firstTokensByLineNumber.get(token.loc.start.line);
218
+ }
219
+
220
+ /**
221
+ * Determines whether a token is the first token in its line
222
+ * @param {Token} token The token
223
+ * @returns {boolean} `true` if the token is the first on its line
224
+ */
225
+ isFirstTokenOfLine(token) {
226
+ return this.getFirstTokenOfLine(token) === token;
227
+ }
228
+
229
+ /**
230
+ * Get the actual indent of a token
231
+ * @param {Token} token Token to examine. This should be the first token on its line.
232
+ * @returns {string} The indentation characters that precede the token
233
+ */
234
+ getTokenIndent(token) {
235
+ return this.sourceCode.text.slice(
236
+ token.range[0] - token.loc.start.column,
237
+ token.range[0],
238
+ );
239
+ }
233
240
  }
234
241
 
235
242
  /**
236
243
  * A class to store information on desired offsets of tokens from each other
237
244
  */
238
245
  class OffsetStorage {
239
-
240
- /**
241
- * @param {TokenInfo} tokenInfo a TokenInfo instance
242
- * @param {number} indentSize The desired size of each indentation level
243
- * @param {string} indentType The indentation character
244
- * @param {number} maxIndex The maximum end index of any token
245
- */
246
- constructor(tokenInfo, indentSize, indentType, maxIndex) {
247
- this._tokenInfo = tokenInfo;
248
- this._indentSize = indentSize;
249
- this._indentType = indentType;
250
-
251
- this._indexMap = new IndexMap(maxIndex);
252
- this._indexMap.insert(0, { offset: 0, from: null, force: false });
253
-
254
- this._lockedFirstTokens = new WeakMap();
255
- this._desiredIndentCache = new WeakMap();
256
- this._ignoredTokens = new WeakSet();
257
- }
258
-
259
- _getOffsetDescriptor(token) {
260
- return this._indexMap.findLastNotAfter(token.range[0]);
261
- }
262
-
263
- /**
264
- * Sets the offset column of token B to match the offset column of token A.
265
- * - **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In
266
- * most cases, `setDesiredOffset` should be used instead.
267
- * @param {Token} baseToken The first token
268
- * @param {Token} offsetToken The second token, whose offset should be matched to the first token
269
- * @returns {void}
270
- */
271
- matchOffsetOf(baseToken, offsetToken) {
272
-
273
- /*
274
- * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to
275
- * the token that it depends on. For example, with the `ArrayExpression: first` option, the first
276
- * token of each element in the array after the first will be mapped to the first token of the first
277
- * element. The desired indentation of each of these tokens is computed based on the desired indentation
278
- * of the "first" element, rather than through the normal offset mechanism.
279
- */
280
- this._lockedFirstTokens.set(offsetToken, baseToken);
281
- }
282
-
283
- /**
284
- * Sets the desired offset of a token.
285
- *
286
- * This uses a line-based offset collapsing behavior to handle tokens on the same line.
287
- * For example, consider the following two cases:
288
- *
289
- * (
290
- * [
291
- * bar
292
- * ]
293
- * )
294
- *
295
- * ([
296
- * bar
297
- * ])
298
- *
299
- * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from
300
- * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is
301
- * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces)
302
- * from the start of its line.
303
- *
304
- * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level
305
- * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the
306
- * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented
307
- * by 1 indent level from the start of the line.
308
- *
309
- * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node,
310
- * without needing to check which lines those tokens are on.
311
- *
312
- * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive
313
- * behavior can occur. For example, consider the following cases:
314
- *
315
- * foo(
316
- * ).
317
- * bar(
318
- * baz
319
- * )
320
- *
321
- * foo(
322
- * ).bar(
323
- * baz
324
- * )
325
- *
326
- * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz`
327
- * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz`
328
- * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no
329
- * collapsing would occur).
330
- *
331
- * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and
332
- * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed
333
- * in the second case.
334
- * @param {Token} token The token
335
- * @param {Token} fromToken The token that `token` should be offset from
336
- * @param {number} offset The desired indent level
337
- * @returns {void}
338
- */
339
- setDesiredOffset(token, fromToken, offset) {
340
- return this.setDesiredOffsets(token.range, fromToken, offset);
341
- }
342
-
343
- /**
344
- * Sets the desired offset of all tokens in a range
345
- * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens.
346
- * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains
347
- * it). This means that the offset of each token is updated O(AST depth) times.
348
- * It would not be performant to store and update the offsets for each token independently, because the rule would end
349
- * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files.
350
- *
351
- * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following
352
- * list could represent the state of the offset tree at a given point:
353
- *
354
- * - Tokens starting in the interval [0, 15) are aligned with the beginning of the file
355
- * - Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token
356
- * - Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token
357
- * - Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token
358
- * - Tokens starting in the interval [820, ∞) are offset by 1 indent level from the `baz` token
359
- *
360
- * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using:
361
- * `setDesiredOffsets([30, 43], fooToken, 1);`
362
- * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied.
363
- * @param {Token} fromToken The token that this is offset from
364
- * @param {number} offset The desired indent level
365
- * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false.
366
- * @returns {void}
367
- */
368
- setDesiredOffsets(range, fromToken, offset, force) {
369
-
370
- /*
371
- * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset
372
- * descriptor. The tree for the example above would have the following nodes:
373
- *
374
- * * key: 0, value: { offset: 0, from: null }
375
- * * key: 15, value: { offset: 1, from: barToken }
376
- * * key: 30, value: { offset: 1, from: fooToken }
377
- * * key: 43, value: { offset: 2, from: barToken }
378
- * * key: 820, value: { offset: 1, from: bazToken }
379
- *
380
- * To find the offset descriptor for any given token, one needs to find the node with the largest key
381
- * which is <= token.start. To make this operation fast, the nodes are stored in a map indexed by key.
382
- */
383
-
384
- const descriptorToInsert = { offset, from: fromToken, force };
385
-
386
- const descriptorAfterRange = this._indexMap.findLastNotAfter(range[1]);
387
-
388
- const fromTokenIsInRange = fromToken && fromToken.range[0] >= range[0] && fromToken.range[1] <= range[1];
389
- const fromTokenDescriptor = fromTokenIsInRange && this._getOffsetDescriptor(fromToken);
390
-
391
- // First, remove any existing nodes in the range from the map.
392
- this._indexMap.deleteRange(range[0] + 1, range[1]);
393
-
394
- // Insert a new node into the map for this range
395
- this._indexMap.insert(range[0], descriptorToInsert);
396
-
397
- /*
398
- * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously,
399
- * even if it's in the current range.
400
- */
401
- if (fromTokenIsInRange) {
402
- this._indexMap.insert(fromToken.range[0], fromTokenDescriptor);
403
- this._indexMap.insert(fromToken.range[1], descriptorToInsert);
404
- }
405
-
406
- /*
407
- * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following
408
- * tokens the same as it was before.
409
- */
410
- this._indexMap.insert(range[1], descriptorAfterRange);
411
- }
412
-
413
- /**
414
- * Gets the desired indent of a token
415
- * @param {Token} token The token
416
- * @returns {string} The desired indent of the token
417
- */
418
- getDesiredIndent(token) {
419
- if (!this._desiredIndentCache.has(token)) {
420
-
421
- if (this._ignoredTokens.has(token)) {
422
-
423
- /*
424
- * If the token is ignored, use the actual indent of the token as the desired indent.
425
- * This ensures that no errors are reported for this token.
426
- */
427
- this._desiredIndentCache.set(
428
- token,
429
- this._tokenInfo.getTokenIndent(token)
430
- );
431
- } else if (this._lockedFirstTokens.has(token)) {
432
- const firstToken = this._lockedFirstTokens.get(token);
433
-
434
- this._desiredIndentCache.set(
435
- token,
436
-
437
- // (indentation for the first element's line)
438
- this.getDesiredIndent(this._tokenInfo.getFirstTokenOfLine(firstToken)) +
439
-
440
- // (space between the start of the first element's line and the first element)
441
- this._indentType.repeat(firstToken.loc.start.column - this._tokenInfo.getFirstTokenOfLine(firstToken).loc.start.column)
442
- );
443
- } else {
444
- const offsetInfo = this._getOffsetDescriptor(token);
445
- const offset = (
446
- offsetInfo.from &&
447
- offsetInfo.from.loc.start.line === token.loc.start.line &&
448
- !/^\s*?\n/u.test(token.value) &&
449
- !offsetInfo.force
450
- ) ? 0 : offsetInfo.offset * this._indentSize;
451
-
452
- this._desiredIndentCache.set(
453
- token,
454
- (offsetInfo.from ? this.getDesiredIndent(offsetInfo.from) : "") + this._indentType.repeat(offset)
455
- );
456
- }
457
- }
458
- return this._desiredIndentCache.get(token);
459
- }
460
-
461
- /**
462
- * Ignores a token, preventing it from being reported.
463
- * @param {Token} token The token
464
- * @returns {void}
465
- */
466
- ignoreToken(token) {
467
- if (this._tokenInfo.isFirstTokenOfLine(token)) {
468
- this._ignoredTokens.add(token);
469
- }
470
- }
471
-
472
- /**
473
- * Gets the first token that the given token's indentation is dependent on
474
- * @param {Token} token The token
475
- * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level
476
- */
477
- getFirstDependency(token) {
478
- return this._getOffsetDescriptor(token).from;
479
- }
246
+ /**
247
+ * @param {TokenInfo} tokenInfo a TokenInfo instance
248
+ * @param {number} indentSize The desired size of each indentation level
249
+ * @param {string} indentType The indentation character
250
+ * @param {number} maxIndex The maximum end index of any token
251
+ */
252
+ constructor(tokenInfo, indentSize, indentType, maxIndex) {
253
+ this._tokenInfo = tokenInfo;
254
+ this._indentSize = indentSize;
255
+ this._indentType = indentType;
256
+
257
+ this._indexMap = new IndexMap(maxIndex);
258
+ this._indexMap.insert(0, { offset: 0, from: null, force: false });
259
+
260
+ this._lockedFirstTokens = new WeakMap();
261
+ this._desiredIndentCache = new WeakMap();
262
+ this._ignoredTokens = new WeakSet();
263
+ }
264
+
265
+ _getOffsetDescriptor(token) {
266
+ return this._indexMap.findLastNotAfter(token.range[0]);
267
+ }
268
+
269
+ /**
270
+ * Sets the offset column of token B to match the offset column of token A.
271
+ * - **WARNING**: This matches a *column*, even if baseToken is not the first token on its line. In
272
+ * most cases, `setDesiredOffset` should be used instead.
273
+ * @param {Token} baseToken The first token
274
+ * @param {Token} offsetToken The second token, whose offset should be matched to the first token
275
+ * @returns {void}
276
+ */
277
+ matchOffsetOf(baseToken, offsetToken) {
278
+ /*
279
+ * lockedFirstTokens is a map from a token whose indentation is controlled by the "first" option to
280
+ * the token that it depends on. For example, with the `ArrayExpression: first` option, the first
281
+ * token of each element in the array after the first will be mapped to the first token of the first
282
+ * element. The desired indentation of each of these tokens is computed based on the desired indentation
283
+ * of the "first" element, rather than through the normal offset mechanism.
284
+ */
285
+ this._lockedFirstTokens.set(offsetToken, baseToken);
286
+ }
287
+
288
+ /**
289
+ * Sets the desired offset of a token.
290
+ *
291
+ * This uses a line-based offset collapsing behavior to handle tokens on the same line.
292
+ * For example, consider the following two cases:
293
+ *
294
+ * (
295
+ * [
296
+ * bar
297
+ * ]
298
+ * )
299
+ *
300
+ * ([
301
+ * bar
302
+ * ])
303
+ *
304
+ * Based on the first case, it's clear that the `bar` token needs to have an offset of 1 indent level (4 spaces) from
305
+ * the `[` token, and the `[` token has to have an offset of 1 indent level from the `(` token. Since the `(` token is
306
+ * the first on its line (with an indent of 0 spaces), the `bar` token needs to be offset by 2 indent levels (8 spaces)
307
+ * from the start of its line.
308
+ *
309
+ * However, in the second case `bar` should only be indented by 4 spaces. This is because the offset of 1 indent level
310
+ * between the `(` and the `[` tokens gets "collapsed" because the two tokens are on the same line. As a result, the
311
+ * `(` token is mapped to the `[` token with an offset of 0, and the rule correctly decides that `bar` should be indented
312
+ * by 1 indent level from the start of the line.
313
+ *
314
+ * This is useful because rule listeners can usually just call `setDesiredOffset` for all the tokens in the node,
315
+ * without needing to check which lines those tokens are on.
316
+ *
317
+ * Note that since collapsing only occurs when two tokens are on the same line, there are a few cases where non-intuitive
318
+ * behavior can occur. For example, consider the following cases:
319
+ *
320
+ * foo(
321
+ * ).
322
+ * bar(
323
+ * baz
324
+ * )
325
+ *
326
+ * foo(
327
+ * ).bar(
328
+ * baz
329
+ * )
330
+ *
331
+ * Based on the first example, it would seem that `bar` should be offset by 1 indent level from `foo`, and `baz`
332
+ * should be offset by 1 indent level from `bar`. However, this is not correct, because it would result in `baz`
333
+ * being indented by 2 indent levels in the second case (since `foo`, `bar`, and `baz` are all on separate lines, no
334
+ * collapsing would occur).
335
+ *
336
+ * Instead, the correct way would be to offset `baz` by 1 level from `bar`, offset `bar` by 1 level from the `)`, and
337
+ * offset the `)` by 0 levels from `foo`. This ensures that the offset between `bar` and the `)` are correctly collapsed
338
+ * in the second case.
339
+ * @param {Token} token The token
340
+ * @param {Token} fromToken The token that `token` should be offset from
341
+ * @param {number} offset The desired indent level
342
+ * @returns {void}
343
+ */
344
+ setDesiredOffset(token, fromToken, offset) {
345
+ return this.setDesiredOffsets(token.range, fromToken, offset);
346
+ }
347
+
348
+ /**
349
+ * Sets the desired offset of all tokens in a range
350
+ * It's common for node listeners in this file to need to apply the same offset to a large, contiguous range of tokens.
351
+ * Moreover, the offset of any given token is usually updated multiple times (roughly once for each node that contains
352
+ * it). This means that the offset of each token is updated O(AST depth) times.
353
+ * It would not be performant to store and update the offsets for each token independently, because the rule would end
354
+ * up having a time complexity of O(number of tokens * AST depth), which is quite slow for large files.
355
+ *
356
+ * Instead, the offset tree is represented as a collection of contiguous offset ranges in a file. For example, the following
357
+ * list could represent the state of the offset tree at a given point:
358
+ *
359
+ * - Tokens starting in the interval [0, 15) are aligned with the beginning of the file
360
+ * - Tokens starting in the interval [15, 30) are offset by 1 indent level from the `bar` token
361
+ * - Tokens starting in the interval [30, 43) are offset by 1 indent level from the `foo` token
362
+ * - Tokens starting in the interval [43, 820) are offset by 2 indent levels from the `bar` token
363
+ * - Tokens starting in the interval [820, ) are offset by 1 indent level from the `baz` token
364
+ *
365
+ * The `setDesiredOffsets` methods inserts ranges like the ones above. The third line above would be inserted by using:
366
+ * `setDesiredOffsets([30, 43], fooToken, 1);`
367
+ * @param {[number, number]} range A [start, end] pair. All tokens with range[0] <= token.start < range[1] will have the offset applied.
368
+ * @param {Token} fromToken The token that this is offset from
369
+ * @param {number} offset The desired indent level
370
+ * @param {boolean} force `true` if this offset should not use the normal collapsing behavior. This should almost always be false.
371
+ * @returns {void}
372
+ */
373
+ setDesiredOffsets(range, fromToken, offset, force) {
374
+ /*
375
+ * Offset ranges are stored as a collection of nodes, where each node maps a numeric key to an offset
376
+ * descriptor. The tree for the example above would have the following nodes:
377
+ *
378
+ * * key: 0, value: { offset: 0, from: null }
379
+ * * key: 15, value: { offset: 1, from: barToken }
380
+ * * key: 30, value: { offset: 1, from: fooToken }
381
+ * * key: 43, value: { offset: 2, from: barToken }
382
+ * * key: 820, value: { offset: 1, from: bazToken }
383
+ *
384
+ * To find the offset descriptor for any given token, one needs to find the node with the largest key
385
+ * which is <= token.start. To make this operation fast, the nodes are stored in a map indexed by key.
386
+ */
387
+
388
+ const descriptorToInsert = { offset, from: fromToken, force };
389
+
390
+ const descriptorAfterRange = this._indexMap.findLastNotAfter(range[1]);
391
+
392
+ const fromTokenIsInRange =
393
+ fromToken &&
394
+ fromToken.range[0] >= range[0] &&
395
+ fromToken.range[1] <= range[1];
396
+ const fromTokenDescriptor =
397
+ fromTokenIsInRange && this._getOffsetDescriptor(fromToken);
398
+
399
+ // First, remove any existing nodes in the range from the map.
400
+ this._indexMap.deleteRange(range[0] + 1, range[1]);
401
+
402
+ // Insert a new node into the map for this range
403
+ this._indexMap.insert(range[0], descriptorToInsert);
404
+
405
+ /*
406
+ * To avoid circular offset dependencies, keep the `fromToken` token mapped to whatever it was mapped to previously,
407
+ * even if it's in the current range.
408
+ */
409
+ if (fromTokenIsInRange) {
410
+ this._indexMap.insert(fromToken.range[0], fromTokenDescriptor);
411
+ this._indexMap.insert(fromToken.range[1], descriptorToInsert);
412
+ }
413
+
414
+ /*
415
+ * To avoid modifying the offset of tokens after the range, insert another node to keep the offset of the following
416
+ * tokens the same as it was before.
417
+ */
418
+ this._indexMap.insert(range[1], descriptorAfterRange);
419
+ }
420
+
421
+ /**
422
+ * Gets the desired indent of a token
423
+ * @param {Token} token The token
424
+ * @returns {string} The desired indent of the token
425
+ */
426
+ getDesiredIndent(token) {
427
+ if (!this._desiredIndentCache.has(token)) {
428
+ if (this._ignoredTokens.has(token)) {
429
+ /*
430
+ * If the token is ignored, use the actual indent of the token as the desired indent.
431
+ * This ensures that no errors are reported for this token.
432
+ */
433
+ this._desiredIndentCache.set(
434
+ token,
435
+ this._tokenInfo.getTokenIndent(token),
436
+ );
437
+ } else if (this._lockedFirstTokens.has(token)) {
438
+ const firstToken = this._lockedFirstTokens.get(token);
439
+
440
+ this._desiredIndentCache.set(
441
+ token,
442
+
443
+ // (indentation for the first element's line)
444
+ this.getDesiredIndent(
445
+ this._tokenInfo.getFirstTokenOfLine(firstToken),
446
+ ) +
447
+ // (space between the start of the first element's line and the first element)
448
+ this._indentType.repeat(
449
+ firstToken.loc.start.column -
450
+ this._tokenInfo.getFirstTokenOfLine(firstToken)
451
+ .loc.start.column,
452
+ ),
453
+ );
454
+ } else {
455
+ const offsetInfo = this._getOffsetDescriptor(token);
456
+ const offset =
457
+ offsetInfo.from &&
458
+ offsetInfo.from.loc.start.line === token.loc.start.line &&
459
+ !/^\s*?\n/u.test(token.value) &&
460
+ !offsetInfo.force
461
+ ? 0
462
+ : offsetInfo.offset * this._indentSize;
463
+
464
+ this._desiredIndentCache.set(
465
+ token,
466
+ (offsetInfo.from
467
+ ? this.getDesiredIndent(offsetInfo.from)
468
+ : "") + this._indentType.repeat(offset),
469
+ );
470
+ }
471
+ }
472
+ return this._desiredIndentCache.get(token);
473
+ }
474
+
475
+ /**
476
+ * Ignores a token, preventing it from being reported.
477
+ * @param {Token} token The token
478
+ * @returns {void}
479
+ */
480
+ ignoreToken(token) {
481
+ if (this._tokenInfo.isFirstTokenOfLine(token)) {
482
+ this._ignoredTokens.add(token);
483
+ }
484
+ }
485
+
486
+ /**
487
+ * Gets the first token that the given token's indentation is dependent on
488
+ * @param {Token} token The token
489
+ * @returns {Token} The token that the given token depends on, or `null` if the given token is at the top level
490
+ */
491
+ getFirstDependency(token) {
492
+ return this._getOffsetDescriptor(token).from;
493
+ }
480
494
  }
481
495
 
482
496
  const ELEMENT_LIST_SCHEMA = {
483
- oneOf: [
484
- {
485
- type: "integer",
486
- minimum: 0
487
- },
488
- {
489
- enum: ["first", "off"]
490
- }
491
- ]
497
+ oneOf: [
498
+ {
499
+ type: "integer",
500
+ minimum: 0,
501
+ },
502
+ {
503
+ enum: ["first", "off"],
504
+ },
505
+ ],
492
506
  };
493
507
 
494
- /** @type {import('../shared/types').Rule} */
508
+ /** @type {import('../types').Rule.RuleModule} */
495
509
  module.exports = {
496
- meta: {
497
- deprecated: {
498
- message: "Formatting rules are being moved out of ESLint core.",
499
- url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
500
- deprecatedSince: "8.53.0",
501
- availableUntil: "10.0.0",
502
- replacedBy: [
503
- {
504
- message: "ESLint Stylistic now maintains deprecated stylistic core rules.",
505
- url: "https://eslint.style/guide/migration",
506
- plugin: {
507
- name: "@stylistic/eslint-plugin-js",
508
- url: "https://eslint.style/packages/js"
509
- },
510
- rule: {
511
- name: "indent",
512
- url: "https://eslint.style/rules/js/indent"
513
- }
514
- }
515
- ]
516
- },
517
- type: "layout",
518
-
519
- docs: {
520
- description: "Enforce consistent indentation",
521
- recommended: false,
522
- url: "https://eslint.org/docs/latest/rules/indent"
523
- },
524
-
525
- fixable: "whitespace",
526
-
527
- schema: [
528
- {
529
- oneOf: [
530
- {
531
- enum: ["tab"]
532
- },
533
- {
534
- type: "integer",
535
- minimum: 0
536
- }
537
- ]
538
- },
539
- {
540
- type: "object",
541
- properties: {
542
- SwitchCase: {
543
- type: "integer",
544
- minimum: 0,
545
- default: 0
546
- },
547
- VariableDeclarator: {
548
- oneOf: [
549
- ELEMENT_LIST_SCHEMA,
550
- {
551
- type: "object",
552
- properties: {
553
- var: ELEMENT_LIST_SCHEMA,
554
- let: ELEMENT_LIST_SCHEMA,
555
- const: ELEMENT_LIST_SCHEMA
556
- },
557
- additionalProperties: false
558
- }
559
- ]
560
- },
561
- outerIIFEBody: {
562
- oneOf: [
563
- {
564
- type: "integer",
565
- minimum: 0
566
- },
567
- {
568
- enum: ["off"]
569
- }
570
- ]
571
- },
572
- MemberExpression: {
573
- oneOf: [
574
- {
575
- type: "integer",
576
- minimum: 0
577
- },
578
- {
579
- enum: ["off"]
580
- }
581
- ]
582
- },
583
- FunctionDeclaration: {
584
- type: "object",
585
- properties: {
586
- parameters: ELEMENT_LIST_SCHEMA,
587
- body: {
588
- type: "integer",
589
- minimum: 0
590
- }
591
- },
592
- additionalProperties: false
593
- },
594
- FunctionExpression: {
595
- type: "object",
596
- properties: {
597
- parameters: ELEMENT_LIST_SCHEMA,
598
- body: {
599
- type: "integer",
600
- minimum: 0
601
- }
602
- },
603
- additionalProperties: false
604
- },
605
- StaticBlock: {
606
- type: "object",
607
- properties: {
608
- body: {
609
- type: "integer",
610
- minimum: 0
611
- }
612
- },
613
- additionalProperties: false
614
- },
615
- CallExpression: {
616
- type: "object",
617
- properties: {
618
- arguments: ELEMENT_LIST_SCHEMA
619
- },
620
- additionalProperties: false
621
- },
622
- ArrayExpression: ELEMENT_LIST_SCHEMA,
623
- ObjectExpression: ELEMENT_LIST_SCHEMA,
624
- ImportDeclaration: ELEMENT_LIST_SCHEMA,
625
- flatTernaryExpressions: {
626
- type: "boolean",
627
- default: false
628
- },
629
- offsetTernaryExpressions: {
630
- type: "boolean",
631
- default: false
632
- },
633
- ignoredNodes: {
634
- type: "array",
635
- items: {
636
- type: "string",
637
- not: {
638
- pattern: ":exit$"
639
- }
640
- }
641
- },
642
- ignoreComments: {
643
- type: "boolean",
644
- default: false
645
- }
646
- },
647
- additionalProperties: false
648
- }
649
- ],
650
- messages: {
651
- wrongIndentation: "Expected indentation of {{expected}} but found {{actual}}."
652
- }
653
- },
654
-
655
- create(context) {
656
- const DEFAULT_VARIABLE_INDENT = 1;
657
- const DEFAULT_PARAMETER_INDENT = 1;
658
- const DEFAULT_FUNCTION_BODY_INDENT = 1;
659
-
660
- let indentType = "space";
661
- let indentSize = 4;
662
- const options = {
663
- SwitchCase: 0,
664
- VariableDeclarator: {
665
- var: DEFAULT_VARIABLE_INDENT,
666
- let: DEFAULT_VARIABLE_INDENT,
667
- const: DEFAULT_VARIABLE_INDENT
668
- },
669
- outerIIFEBody: 1,
670
- FunctionDeclaration: {
671
- parameters: DEFAULT_PARAMETER_INDENT,
672
- body: DEFAULT_FUNCTION_BODY_INDENT
673
- },
674
- FunctionExpression: {
675
- parameters: DEFAULT_PARAMETER_INDENT,
676
- body: DEFAULT_FUNCTION_BODY_INDENT
677
- },
678
- StaticBlock: {
679
- body: DEFAULT_FUNCTION_BODY_INDENT
680
- },
681
- CallExpression: {
682
- arguments: DEFAULT_PARAMETER_INDENT
683
- },
684
- MemberExpression: 1,
685
- ArrayExpression: 1,
686
- ObjectExpression: 1,
687
- ImportDeclaration: 1,
688
- flatTernaryExpressions: false,
689
- ignoredNodes: [],
690
- ignoreComments: false
691
- };
692
-
693
- if (context.options.length) {
694
- if (context.options[0] === "tab") {
695
- indentSize = 1;
696
- indentType = "tab";
697
- } else {
698
- indentSize = context.options[0];
699
- indentType = "space";
700
- }
701
-
702
- if (context.options[1]) {
703
- Object.assign(options, context.options[1]);
704
-
705
- if (typeof options.VariableDeclarator === "number" || options.VariableDeclarator === "first") {
706
- options.VariableDeclarator = {
707
- var: options.VariableDeclarator,
708
- let: options.VariableDeclarator,
709
- const: options.VariableDeclarator
710
- };
711
- }
712
- }
713
- }
714
-
715
- const sourceCode = context.sourceCode;
716
- const tokenInfo = new TokenInfo(sourceCode);
717
- const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t", sourceCode.text.length);
718
- const parameterParens = new WeakSet();
719
-
720
- /**
721
- * Creates an error message for a line, given the expected/actual indentation.
722
- * @param {int} expectedAmount The expected amount of indentation characters for this line
723
- * @param {int} actualSpaces The actual number of indentation spaces that were found on this line
724
- * @param {int} actualTabs The actual number of indentation tabs that were found on this line
725
- * @returns {string} An error message for this line
726
- */
727
- function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) {
728
- const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs"
729
- const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space"
730
- const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs"
731
- let foundStatement;
732
-
733
- if (actualSpaces > 0) {
734
-
735
- /*
736
- * Abbreviate the message if the expected indentation is also spaces.
737
- * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
738
- */
739
- foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`;
740
- } else if (actualTabs > 0) {
741
- foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`;
742
- } else {
743
- foundStatement = "0";
744
- }
745
- return {
746
- expected: expectedStatement,
747
- actual: foundStatement
748
- };
749
- }
750
-
751
- /**
752
- * Reports a given indent violation
753
- * @param {Token} token Token violating the indent rule
754
- * @param {string} neededIndent Expected indentation string
755
- * @returns {void}
756
- */
757
- function report(token, neededIndent) {
758
- const actualIndent = Array.from(tokenInfo.getTokenIndent(token));
759
- const numSpaces = actualIndent.filter(char => char === " ").length;
760
- const numTabs = actualIndent.filter(char => char === "\t").length;
761
-
762
- context.report({
763
- node: token,
764
- messageId: "wrongIndentation",
765
- data: createErrorMessageData(neededIndent.length, numSpaces, numTabs),
766
- loc: {
767
- start: { line: token.loc.start.line, column: 0 },
768
- end: { line: token.loc.start.line, column: token.loc.start.column }
769
- },
770
- fix(fixer) {
771
- const range = [token.range[0] - token.loc.start.column, token.range[0]];
772
- const newText = neededIndent;
773
-
774
- return fixer.replaceTextRange(range, newText);
775
- }
776
- });
777
- }
778
-
779
- /**
780
- * Checks if a token's indentation is correct
781
- * @param {Token} token Token to examine
782
- * @param {string} desiredIndent Desired indentation of the string
783
- * @returns {boolean} `true` if the token's indentation is correct
784
- */
785
- function validateTokenIndent(token, desiredIndent) {
786
- const indentation = tokenInfo.getTokenIndent(token);
787
-
788
- return indentation === desiredIndent ||
789
-
790
- // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
791
- indentation.includes(" ") && indentation.includes("\t");
792
- }
793
-
794
- /**
795
- * Check to see if the node is a file level IIFE
796
- * @param {ASTNode} node The function node to check.
797
- * @returns {boolean} True if the node is the outer IIFE
798
- */
799
- function isOuterIIFE(node) {
800
-
801
- /*
802
- * Verify that the node is an IIFE
803
- */
804
- if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) {
805
- return false;
806
- }
807
-
808
- /*
809
- * Navigate legal ancestors to determine whether this IIFE is outer.
810
- * A "legal ancestor" is an expression or statement that causes the function to get executed immediately.
811
- * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator.
812
- */
813
- let statement = node.parent && node.parent.parent;
814
-
815
- while (
816
- statement.type === "UnaryExpression" && ["!", "~", "+", "-"].includes(statement.operator) ||
817
- statement.type === "AssignmentExpression" ||
818
- statement.type === "LogicalExpression" ||
819
- statement.type === "SequenceExpression" ||
820
- statement.type === "VariableDeclarator"
821
- ) {
822
- statement = statement.parent;
823
- }
824
-
825
- return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program";
826
- }
827
-
828
- /**
829
- * Counts the number of linebreaks that follow the last non-whitespace character in a string
830
- * @param {string} string The string to check
831
- * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character,
832
- * or the total number of linebreaks if the string is all whitespace.
833
- */
834
- function countTrailingLinebreaks(string) {
835
- const trailingWhitespace = string.match(/\s*$/u)[0];
836
- const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher());
837
-
838
- return linebreakMatches === null ? 0 : linebreakMatches.length;
839
- }
840
-
841
- /**
842
- * Check indentation for lists of elements (arrays, objects, function params)
843
- * @param {ASTNode[]} elements List of elements that should be offset
844
- * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '['
845
- * @param {Token} endToken The end token of the list, e.g. ']'
846
- * @param {number|string} offset The amount that the elements should be offset
847
- * @returns {void}
848
- */
849
- function addElementListIndent(elements, startToken, endToken, offset) {
850
-
851
- /**
852
- * Gets the first token of a given element, including surrounding parentheses.
853
- * @param {ASTNode} element A node in the `elements` list
854
- * @returns {Token} The first token of this element
855
- */
856
- function getFirstToken(element) {
857
- let token = sourceCode.getTokenBefore(element);
858
-
859
- while (astUtils.isOpeningParenToken(token) && token !== startToken) {
860
- token = sourceCode.getTokenBefore(token);
861
- }
862
- return sourceCode.getTokenAfter(token);
863
- }
864
-
865
- // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden)
866
- offsets.setDesiredOffsets(
867
- [startToken.range[1], endToken.range[0]],
868
- startToken,
869
- typeof offset === "number" ? offset : 1
870
- );
871
- offsets.setDesiredOffset(endToken, startToken, 0);
872
-
873
- // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level.
874
- if (offset === "first" && elements.length && !elements[0]) {
875
- return;
876
- }
877
- elements.forEach((element, index) => {
878
- if (!element) {
879
-
880
- // Skip holes in arrays
881
- return;
882
- }
883
- if (offset === "off") {
884
-
885
- // Ignore the first token of every element if the "off" option is used
886
- offsets.ignoreToken(getFirstToken(element));
887
- }
888
-
889
- // Offset the following elements correctly relative to the first element
890
- if (index === 0) {
891
- return;
892
- }
893
- if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) {
894
- offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element));
895
- } else {
896
- const previousElement = elements[index - 1];
897
- const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement);
898
- const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement);
899
-
900
- if (
901
- previousElement &&
902
- previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line
903
- ) {
904
- offsets.setDesiredOffsets(
905
- [previousElement.range[1], element.range[1]],
906
- firstTokenOfPreviousElement,
907
- 0
908
- );
909
- }
910
- }
911
- });
912
- }
913
-
914
- /**
915
- * Check and decide whether to check for indentation for blockless nodes
916
- * Scenarios are for or while statements without braces around them
917
- * @param {ASTNode} node node to examine
918
- * @returns {void}
919
- */
920
- function addBlocklessNodeIndent(node) {
921
- if (node.type !== "BlockStatement") {
922
- const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken);
923
-
924
- let firstBodyToken = sourceCode.getFirstToken(node);
925
- let lastBodyToken = sourceCode.getLastToken(node);
926
-
927
- while (
928
- astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) &&
929
- astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken))
930
- ) {
931
- firstBodyToken = sourceCode.getTokenBefore(firstBodyToken);
932
- lastBodyToken = sourceCode.getTokenAfter(lastBodyToken);
933
- }
934
-
935
- offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
936
- }
937
- }
938
-
939
- /**
940
- * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`)
941
- * @param {ASTNode} node A CallExpression or NewExpression node
942
- * @returns {void}
943
- */
944
- function addFunctionCallIndent(node) {
945
- let openingParen;
946
-
947
- if (node.arguments.length) {
948
- openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken);
949
- } else {
950
- openingParen = sourceCode.getLastToken(node, 1);
951
- }
952
- const closingParen = sourceCode.getLastToken(node);
953
-
954
- parameterParens.add(openingParen);
955
- parameterParens.add(closingParen);
956
-
957
- /*
958
- * If `?.` token exists, set desired offset for that.
959
- * This logic is copied from `MemberExpression`'s.
960
- */
961
- if (node.optional) {
962
- const dotToken = sourceCode.getTokenAfter(node.callee, astUtils.isQuestionDotToken);
963
- const calleeParenCount = sourceCode.getTokensBetween(node.callee, dotToken, { filter: astUtils.isClosingParenToken }).length;
964
- const firstTokenOfCallee = calleeParenCount
965
- ? sourceCode.getTokenBefore(node.callee, { skip: calleeParenCount - 1 })
966
- : sourceCode.getFirstToken(node.callee);
967
- const lastTokenOfCallee = sourceCode.getTokenBefore(dotToken);
968
- const offsetBase = lastTokenOfCallee.loc.end.line === openingParen.loc.start.line
969
- ? lastTokenOfCallee
970
- : firstTokenOfCallee;
971
-
972
- offsets.setDesiredOffset(dotToken, offsetBase, 1);
973
- }
974
-
975
- const offsetAfterToken = node.callee.type === "TaggedTemplateExpression" ? sourceCode.getFirstToken(node.callee.quasi) : openingParen;
976
- const offsetToken = sourceCode.getTokenBefore(offsetAfterToken);
977
-
978
- offsets.setDesiredOffset(openingParen, offsetToken, 0);
979
-
980
- addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments);
981
- }
982
-
983
- /**
984
- * Checks the indentation of parenthesized values, given a list of tokens in a program
985
- * @param {Token[]} tokens A list of tokens
986
- * @returns {void}
987
- */
988
- function addParensIndent(tokens) {
989
- const parenStack = [];
990
- const parenPairs = [];
991
-
992
- for (let i = 0; i < tokens.length; i++) {
993
- const nextToken = tokens[i];
994
-
995
- if (astUtils.isOpeningParenToken(nextToken)) {
996
- parenStack.push(nextToken);
997
- } else if (astUtils.isClosingParenToken(nextToken)) {
998
- parenPairs.push({ left: parenStack.pop(), right: nextToken });
999
- }
1000
- }
1001
-
1002
- for (let i = parenPairs.length - 1; i >= 0; i--) {
1003
- const leftParen = parenPairs[i].left;
1004
- const rightParen = parenPairs[i].right;
1005
-
1006
- // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.
1007
- if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) {
1008
- const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen));
1009
-
1010
- parenthesizedTokens.forEach(token => {
1011
- if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) {
1012
- offsets.setDesiredOffset(token, leftParen, 1);
1013
- }
1014
- });
1015
- }
1016
-
1017
- offsets.setDesiredOffset(rightParen, leftParen, 0);
1018
- }
1019
- }
1020
-
1021
- /**
1022
- * Ignore all tokens within an unknown node whose offset do not depend
1023
- * on another token's offset within the unknown node
1024
- * @param {ASTNode} node Unknown Node
1025
- * @returns {void}
1026
- */
1027
- function ignoreNode(node) {
1028
- const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true }));
1029
-
1030
- unknownNodeTokens.forEach(token => {
1031
- if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) {
1032
- const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token);
1033
-
1034
- if (token === firstTokenOfLine) {
1035
- offsets.ignoreToken(token);
1036
- } else {
1037
- offsets.setDesiredOffset(token, firstTokenOfLine, 0);
1038
- }
1039
- }
1040
- });
1041
- }
1042
-
1043
- /**
1044
- * Check whether the given token is on the first line of a statement.
1045
- * @param {Token} token The token to check.
1046
- * @param {ASTNode} leafNode The expression node that the token belongs directly.
1047
- * @returns {boolean} `true` if the token is on the first line of a statement.
1048
- */
1049
- function isOnFirstLineOfStatement(token, leafNode) {
1050
- let node = leafNode;
1051
-
1052
- while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) {
1053
- node = node.parent;
1054
- }
1055
- node = node.parent;
1056
-
1057
- return !node || node.loc.start.line === token.loc.start.line;
1058
- }
1059
-
1060
- /**
1061
- * Check whether there are any blank (whitespace-only) lines between
1062
- * two tokens on separate lines.
1063
- * @param {Token} firstToken The first token.
1064
- * @param {Token} secondToken The second token.
1065
- * @returns {boolean} `true` if the tokens are on separate lines and
1066
- * there exists a blank line between them, `false` otherwise.
1067
- */
1068
- function hasBlankLinesBetween(firstToken, secondToken) {
1069
- const firstTokenLine = firstToken.loc.end.line;
1070
- const secondTokenLine = secondToken.loc.start.line;
1071
-
1072
- if (firstTokenLine === secondTokenLine || firstTokenLine === secondTokenLine - 1) {
1073
- return false;
1074
- }
1075
-
1076
- for (let line = firstTokenLine + 1; line < secondTokenLine; ++line) {
1077
- if (!tokenInfo.firstTokensByLineNumber.has(line)) {
1078
- return true;
1079
- }
1080
- }
1081
-
1082
- return false;
1083
- }
1084
-
1085
- const ignoredNodeFirstTokens = new Set();
1086
-
1087
- const baseOffsetListeners = {
1088
- "ArrayExpression, ArrayPattern"(node) {
1089
- const openingBracket = sourceCode.getFirstToken(node);
1090
- const closingBracket = sourceCode.getTokenAfter([...node.elements].reverse().find(_ => _) || openingBracket, astUtils.isClosingBracketToken);
1091
-
1092
- addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression);
1093
- },
1094
-
1095
- "ObjectExpression, ObjectPattern"(node) {
1096
- const openingCurly = sourceCode.getFirstToken(node);
1097
- const closingCurly = sourceCode.getTokenAfter(
1098
- node.properties.length ? node.properties.at(-1) : openingCurly,
1099
- astUtils.isClosingBraceToken
1100
- );
1101
-
1102
- addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression);
1103
- },
1104
-
1105
- ArrowFunctionExpression(node) {
1106
- const maybeOpeningParen = sourceCode.getFirstToken(node, { skip: node.async ? 1 : 0 });
1107
-
1108
- if (astUtils.isOpeningParenToken(maybeOpeningParen)) {
1109
- const openingParen = maybeOpeningParen;
1110
- const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken);
1111
-
1112
- parameterParens.add(openingParen);
1113
- parameterParens.add(closingParen);
1114
- addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters);
1115
- }
1116
-
1117
- addBlocklessNodeIndent(node.body);
1118
- },
1119
-
1120
- AssignmentExpression(node) {
1121
- const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
1122
-
1123
- offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1);
1124
- offsets.ignoreToken(operator);
1125
- offsets.ignoreToken(sourceCode.getTokenAfter(operator));
1126
- },
1127
-
1128
- "BinaryExpression, LogicalExpression"(node) {
1129
- const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
1130
-
1131
- /*
1132
- * For backwards compatibility, don't check BinaryExpression indents, e.g.
1133
- * var foo = bar &&
1134
- * baz;
1135
- */
1136
-
1137
- const tokenAfterOperator = sourceCode.getTokenAfter(operator);
1138
-
1139
- offsets.ignoreToken(operator);
1140
- offsets.ignoreToken(tokenAfterOperator);
1141
- offsets.setDesiredOffset(tokenAfterOperator, operator, 0);
1142
- },
1143
-
1144
- "BlockStatement, ClassBody"(node) {
1145
- let blockIndentLevel;
1146
-
1147
- if (node.parent && isOuterIIFE(node.parent)) {
1148
- blockIndentLevel = options.outerIIFEBody;
1149
- } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) {
1150
- blockIndentLevel = options.FunctionExpression.body;
1151
- } else if (node.parent && node.parent.type === "FunctionDeclaration") {
1152
- blockIndentLevel = options.FunctionDeclaration.body;
1153
- } else {
1154
- blockIndentLevel = 1;
1155
- }
1156
-
1157
- /*
1158
- * For blocks that aren't lone statements, ensure that the opening curly brace
1159
- * is aligned with the parent.
1160
- */
1161
- if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
1162
- offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0);
1163
- }
1164
-
1165
- addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel);
1166
- },
1167
-
1168
- CallExpression: addFunctionCallIndent,
1169
-
1170
- "ClassDeclaration[superClass], ClassExpression[superClass]"(node) {
1171
- const classToken = sourceCode.getFirstToken(node);
1172
- const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken);
1173
-
1174
- offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1);
1175
- },
1176
-
1177
- ConditionalExpression(node) {
1178
- const firstToken = sourceCode.getFirstToken(node);
1179
-
1180
- // `flatTernaryExpressions` option is for the following style:
1181
- // var a =
1182
- // foo > 0 ? bar :
1183
- // foo < 0 ? baz :
1184
- // /*else*/ qiz ;
1185
- if (!options.flatTernaryExpressions ||
1186
- !astUtils.isTokenOnSameLine(node.test, node.consequent) ||
1187
- isOnFirstLineOfStatement(firstToken, node)
1188
- ) {
1189
- const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?");
1190
- const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":");
1191
-
1192
- const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken);
1193
- const lastConsequentToken = sourceCode.getTokenBefore(colonToken);
1194
- const firstAlternateToken = sourceCode.getTokenAfter(colonToken);
1195
-
1196
- offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
1197
- offsets.setDesiredOffset(colonToken, firstToken, 1);
1198
-
1199
- offsets.setDesiredOffset(firstConsequentToken, firstToken, firstConsequentToken.type === "Punctuator" &&
1200
- options.offsetTernaryExpressions ? 2 : 1);
1201
-
1202
- /*
1203
- * The alternate and the consequent should usually have the same indentation.
1204
- * If they share part of a line, align the alternate against the first token of the consequent.
1205
- * This allows the alternate to be indented correctly in cases like this:
1206
- * foo ? (
1207
- * bar
1208
- * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo`
1209
- * baz // as a result, `baz` is offset by 1 rather than 2
1210
- * )
1211
- */
1212
- if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) {
1213
- offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0);
1214
- } else {
1215
-
1216
- /**
1217
- * If the alternate and consequent do not share part of a line, offset the alternate from the first
1218
- * token of the conditional expression. For example:
1219
- * foo ? bar
1220
- * : baz
1221
- *
1222
- * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
1223
- * having no expected indentation.
1224
- */
1225
- offsets.setDesiredOffset(firstAlternateToken, firstToken, firstAlternateToken.type === "Punctuator" &&
1226
- options.offsetTernaryExpressions ? 2 : 1);
1227
- }
1228
- }
1229
- },
1230
-
1231
- "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement, WithStatement": node => addBlocklessNodeIndent(node.body),
1232
-
1233
- ExportNamedDeclaration(node) {
1234
- if (node.declaration === null) {
1235
- const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
1236
-
1237
- // Indent the specifiers in `export {foo, bar, baz}`
1238
- addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, { skip: 1 }), closingCurly, 1);
1239
-
1240
- if (node.source) {
1241
-
1242
- // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'`
1243
- offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1);
1244
- }
1245
- }
1246
- },
1247
-
1248
- ForStatement(node) {
1249
- const forOpeningParen = sourceCode.getFirstToken(node, 1);
1250
-
1251
- if (node.init) {
1252
- offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1);
1253
- }
1254
- if (node.test) {
1255
- offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1);
1256
- }
1257
- if (node.update) {
1258
- offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1);
1259
- }
1260
- addBlocklessNodeIndent(node.body);
1261
- },
1262
-
1263
- "FunctionDeclaration, FunctionExpression"(node) {
1264
- const closingParen = sourceCode.getTokenBefore(node.body);
1265
- const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen);
1266
-
1267
- parameterParens.add(openingParen);
1268
- parameterParens.add(closingParen);
1269
- addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters);
1270
- },
1271
-
1272
- IfStatement(node) {
1273
- addBlocklessNodeIndent(node.consequent);
1274
- if (node.alternate) {
1275
- addBlocklessNodeIndent(node.alternate);
1276
- }
1277
- },
1278
-
1279
- /*
1280
- * For blockless nodes with semicolon-first style, don't indent the semicolon.
1281
- * e.g.
1282
- * if (foo)
1283
- * bar()
1284
- * ; [1, 2, 3].map(foo)
1285
- *
1286
- * Traversal into the node sets indentation of the semicolon, so we need to override it on exit.
1287
- */
1288
- ":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement, WithStatement):exit"(node) {
1289
- let nodesToCheck;
1290
-
1291
- if (node.type === "IfStatement") {
1292
- nodesToCheck = [node.consequent];
1293
- if (node.alternate) {
1294
- nodesToCheck.push(node.alternate);
1295
- }
1296
- } else {
1297
- nodesToCheck = [node.body];
1298
- }
1299
-
1300
- for (const nodeToCheck of nodesToCheck) {
1301
- const lastToken = sourceCode.getLastToken(nodeToCheck);
1302
-
1303
- if (astUtils.isSemicolonToken(lastToken)) {
1304
- const tokenBeforeLast = sourceCode.getTokenBefore(lastToken);
1305
- const tokenAfterLast = sourceCode.getTokenAfter(lastToken);
1306
-
1307
- // override indentation of `;` only if its line looks like a semicolon-first style line
1308
- if (
1309
- !astUtils.isTokenOnSameLine(tokenBeforeLast, lastToken) &&
1310
- tokenAfterLast &&
1311
- astUtils.isTokenOnSameLine(lastToken, tokenAfterLast)
1312
- ) {
1313
- offsets.setDesiredOffset(
1314
- lastToken,
1315
- sourceCode.getFirstToken(node),
1316
- 0
1317
- );
1318
- }
1319
- }
1320
- }
1321
- },
1322
-
1323
- ImportDeclaration(node) {
1324
- if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
1325
- const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);
1326
- const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
1327
-
1328
- addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration);
1329
- }
1330
-
1331
- const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from");
1332
- const sourceToken = sourceCode.getLastToken(node, token => token.type === "String");
1333
- const semiToken = sourceCode.getLastToken(node, token => token.type === "Punctuator" && token.value === ";");
1334
-
1335
- if (fromToken) {
1336
- const end = semiToken && semiToken.range[1] === sourceToken.range[1] ? node.range[1] : sourceToken.range[1];
1337
-
1338
- offsets.setDesiredOffsets([fromToken.range[0], end], sourceCode.getFirstToken(node), 1);
1339
- }
1340
- },
1341
-
1342
- ImportExpression(node) {
1343
- const openingParen = sourceCode.getFirstToken(node, 1);
1344
- const closingParen = sourceCode.getLastToken(node);
1345
-
1346
- parameterParens.add(openingParen);
1347
- parameterParens.add(closingParen);
1348
- offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0);
1349
-
1350
- addElementListIndent([node.source], openingParen, closingParen, options.CallExpression.arguments);
1351
- },
1352
-
1353
- "MemberExpression, JSXMemberExpression, MetaProperty"(node) {
1354
- const object = node.type === "MetaProperty" ? node.meta : node.object;
1355
- const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken);
1356
- const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken);
1357
-
1358
- const objectParenCount = sourceCode.getTokensBetween(object, node.property, { filter: astUtils.isClosingParenToken }).length;
1359
- const firstObjectToken = objectParenCount
1360
- ? sourceCode.getTokenBefore(object, { skip: objectParenCount - 1 })
1361
- : sourceCode.getFirstToken(object);
1362
- const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken);
1363
- const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken;
1364
-
1365
- if (node.computed) {
1366
-
1367
- // For computed MemberExpressions, match the closing bracket with the opening bracket.
1368
- offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0);
1369
- offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1);
1370
- }
1371
-
1372
- /*
1373
- * If the object ends on the same line that the property starts, match against the last token
1374
- * of the object, to ensure that the MemberExpression is not indented.
1375
- *
1376
- * Otherwise, match against the first token of the object, e.g.
1377
- * foo
1378
- * .bar
1379
- * .baz // <-- offset by 1 from `foo`
1380
- */
1381
- const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line
1382
- ? lastObjectToken
1383
- : firstObjectToken;
1384
-
1385
- if (typeof options.MemberExpression === "number") {
1386
-
1387
- // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object.
1388
- offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression);
1389
-
1390
- /*
1391
- * For computed MemberExpressions, match the first token of the property against the opening bracket.
1392
- * Otherwise, match the first token of the property against the object.
1393
- */
1394
- offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression);
1395
- } else {
1396
-
1397
- // If the MemberExpression option is off, ignore the dot and the first token of the property.
1398
- offsets.ignoreToken(firstNonObjectToken);
1399
- offsets.ignoreToken(secondNonObjectToken);
1400
-
1401
- // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens.
1402
- offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0);
1403
- offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0);
1404
- }
1405
- },
1406
-
1407
- NewExpression(node) {
1408
-
1409
- // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo`
1410
- if (node.arguments.length > 0 ||
1411
- astUtils.isClosingParenToken(sourceCode.getLastToken(node)) &&
1412
- astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) {
1413
- addFunctionCallIndent(node);
1414
- }
1415
- },
1416
-
1417
- Property(node) {
1418
- if (!node.shorthand && !node.method && node.kind === "init") {
1419
- const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken);
1420
-
1421
- offsets.ignoreToken(sourceCode.getTokenAfter(colon));
1422
- }
1423
- },
1424
-
1425
- PropertyDefinition(node) {
1426
- const firstToken = sourceCode.getFirstToken(node);
1427
- const maybeSemicolonToken = sourceCode.getLastToken(node);
1428
- let keyLastToken;
1429
-
1430
- // Indent key.
1431
- if (node.computed) {
1432
- const bracketTokenL = sourceCode.getTokenBefore(node.key, astUtils.isOpeningBracketToken);
1433
- const bracketTokenR = keyLastToken = sourceCode.getTokenAfter(node.key, astUtils.isClosingBracketToken);
1434
- const keyRange = [bracketTokenL.range[1], bracketTokenR.range[0]];
1435
-
1436
- if (bracketTokenL !== firstToken) {
1437
- offsets.setDesiredOffset(bracketTokenL, firstToken, 0);
1438
- }
1439
- offsets.setDesiredOffsets(keyRange, bracketTokenL, 1);
1440
- offsets.setDesiredOffset(bracketTokenR, bracketTokenL, 0);
1441
- } else {
1442
- const idToken = keyLastToken = sourceCode.getFirstToken(node.key);
1443
-
1444
- if (idToken !== firstToken) {
1445
- offsets.setDesiredOffset(idToken, firstToken, 1);
1446
- }
1447
- }
1448
-
1449
- // Indent initializer.
1450
- if (node.value) {
1451
- const eqToken = sourceCode.getTokenBefore(node.value, astUtils.isEqToken);
1452
- const valueToken = sourceCode.getTokenAfter(eqToken);
1453
-
1454
- offsets.setDesiredOffset(eqToken, keyLastToken, 1);
1455
- offsets.setDesiredOffset(valueToken, eqToken, 1);
1456
- if (astUtils.isSemicolonToken(maybeSemicolonToken)) {
1457
- offsets.setDesiredOffset(maybeSemicolonToken, eqToken, 1);
1458
- }
1459
- } else if (astUtils.isSemicolonToken(maybeSemicolonToken)) {
1460
- offsets.setDesiredOffset(maybeSemicolonToken, keyLastToken, 1);
1461
- }
1462
- },
1463
-
1464
- StaticBlock(node) {
1465
- const openingCurly = sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token
1466
- const closingCurly = sourceCode.getLastToken(node);
1467
-
1468
- addElementListIndent(node.body, openingCurly, closingCurly, options.StaticBlock.body);
1469
- },
1470
-
1471
- SwitchStatement(node) {
1472
- const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken);
1473
- const closingCurly = sourceCode.getLastToken(node);
1474
-
1475
- offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase);
1476
-
1477
- if (node.cases.length) {
1478
- sourceCode.getTokensBetween(
1479
- node.cases.at(-1),
1480
- closingCurly,
1481
- { includeComments: true, filter: astUtils.isCommentToken }
1482
- ).forEach(token => offsets.ignoreToken(token));
1483
- }
1484
- },
1485
-
1486
- SwitchCase(node) {
1487
- if (!(node.consequent.length === 1 && node.consequent[0].type === "BlockStatement")) {
1488
- const caseKeyword = sourceCode.getFirstToken(node);
1489
- const tokenAfterCurrentCase = sourceCode.getTokenAfter(node);
1490
-
1491
- offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1);
1492
- }
1493
- },
1494
-
1495
- TemplateLiteral(node) {
1496
- node.expressions.forEach((expression, index) => {
1497
- const previousQuasi = node.quasis[index];
1498
- const nextQuasi = node.quasis[index + 1];
1499
- const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line
1500
- ? sourceCode.getFirstToken(previousQuasi)
1501
- : null;
1502
-
1503
- offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1);
1504
- offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0);
1505
- });
1506
- },
1507
-
1508
- VariableDeclaration(node) {
1509
- let variableIndent = Object.hasOwn(options.VariableDeclarator, node.kind)
1510
- ? options.VariableDeclarator[node.kind]
1511
- : DEFAULT_VARIABLE_INDENT;
1512
-
1513
- const firstToken = sourceCode.getFirstToken(node),
1514
- lastToken = sourceCode.getLastToken(node);
1515
-
1516
- if (options.VariableDeclarator[node.kind] === "first") {
1517
- if (node.declarations.length > 1) {
1518
- addElementListIndent(
1519
- node.declarations,
1520
- firstToken,
1521
- lastToken,
1522
- "first"
1523
- );
1524
- return;
1525
- }
1526
-
1527
- variableIndent = DEFAULT_VARIABLE_INDENT;
1528
- }
1529
-
1530
- if (node.declarations.at(-1).loc.start.line > node.loc.start.line) {
1531
-
1532
- /*
1533
- * VariableDeclarator indentation is a bit different from other forms of indentation, in that the
1534
- * indentation of an opening bracket sometimes won't match that of a closing bracket. For example,
1535
- * the following indentations are correct:
1536
- *
1537
- * var foo = {
1538
- * ok: true
1539
- * };
1540
- *
1541
- * var foo = {
1542
- * ok: true,
1543
- * },
1544
- * bar = 1;
1545
- *
1546
- * Account for when exiting the AST (after indentations have already been set for the nodes in
1547
- * the declaration) by manually increasing the indentation level of the tokens in this declarator
1548
- * on the same line as the start of the declaration, provided that there are declarators that
1549
- * follow this one.
1550
- */
1551
- offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true);
1552
- } else {
1553
- offsets.setDesiredOffsets(node.range, firstToken, variableIndent);
1554
- }
1555
-
1556
- if (astUtils.isSemicolonToken(lastToken)) {
1557
- offsets.ignoreToken(lastToken);
1558
- }
1559
- },
1560
-
1561
- VariableDeclarator(node) {
1562
- if (node.init) {
1563
- const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken);
1564
- const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator);
1565
-
1566
- offsets.ignoreToken(equalOperator);
1567
- offsets.ignoreToken(tokenAfterOperator);
1568
- offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1);
1569
- offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0);
1570
- }
1571
- },
1572
-
1573
- "JSXAttribute[value]"(node) {
1574
- const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "=");
1575
-
1576
- offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1);
1577
- },
1578
-
1579
- JSXElement(node) {
1580
- if (node.closingElement) {
1581
- addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1);
1582
- }
1583
- },
1584
-
1585
- JSXOpeningElement(node) {
1586
- const firstToken = sourceCode.getFirstToken(node);
1587
- let closingToken;
1588
-
1589
- if (node.selfClosing) {
1590
- closingToken = sourceCode.getLastToken(node, { skip: 1 });
1591
- offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0);
1592
- } else {
1593
- closingToken = sourceCode.getLastToken(node);
1594
- }
1595
- offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node));
1596
- addElementListIndent(node.attributes, firstToken, closingToken, 1);
1597
- },
1598
-
1599
- JSXClosingElement(node) {
1600
- const firstToken = sourceCode.getFirstToken(node);
1601
-
1602
- offsets.setDesiredOffsets(node.name.range, firstToken, 1);
1603
- },
1604
-
1605
- JSXFragment(node) {
1606
- const firstOpeningToken = sourceCode.getFirstToken(node.openingFragment);
1607
- const firstClosingToken = sourceCode.getFirstToken(node.closingFragment);
1608
-
1609
- addElementListIndent(node.children, firstOpeningToken, firstClosingToken, 1);
1610
- },
1611
-
1612
- JSXOpeningFragment(node) {
1613
- const firstToken = sourceCode.getFirstToken(node);
1614
- const closingToken = sourceCode.getLastToken(node);
1615
-
1616
- offsets.setDesiredOffsets(node.range, firstToken, 1);
1617
- offsets.matchOffsetOf(firstToken, closingToken);
1618
- },
1619
-
1620
- JSXClosingFragment(node) {
1621
- const firstToken = sourceCode.getFirstToken(node);
1622
- const slashToken = sourceCode.getLastToken(node, { skip: 1 });
1623
- const closingToken = sourceCode.getLastToken(node);
1624
- const tokenToMatch = astUtils.isTokenOnSameLine(slashToken, closingToken) ? slashToken : closingToken;
1625
-
1626
- offsets.setDesiredOffsets(node.range, firstToken, 1);
1627
- offsets.matchOffsetOf(firstToken, tokenToMatch);
1628
- },
1629
-
1630
- JSXExpressionContainer(node) {
1631
- const openingCurly = sourceCode.getFirstToken(node);
1632
- const closingCurly = sourceCode.getLastToken(node);
1633
-
1634
- offsets.setDesiredOffsets(
1635
- [openingCurly.range[1], closingCurly.range[0]],
1636
- openingCurly,
1637
- 1
1638
- );
1639
- },
1640
-
1641
- JSXSpreadAttribute(node) {
1642
- const openingCurly = sourceCode.getFirstToken(node);
1643
- const closingCurly = sourceCode.getLastToken(node);
1644
-
1645
- offsets.setDesiredOffsets(
1646
- [openingCurly.range[1], closingCurly.range[0]],
1647
- openingCurly,
1648
- 1
1649
- );
1650
- },
1651
-
1652
- "*"(node) {
1653
- const firstToken = sourceCode.getFirstToken(node);
1654
-
1655
- // Ensure that the children of every node are indented at least as much as the first token.
1656
- if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) {
1657
- offsets.setDesiredOffsets(node.range, firstToken, 0);
1658
- }
1659
- }
1660
- };
1661
-
1662
- const listenerCallQueue = [];
1663
-
1664
- /*
1665
- * To ignore the indentation of a node:
1666
- * 1. Don't call the node's listener when entering it (if it has a listener)
1667
- * 2. Don't set any offsets against the first token of the node.
1668
- * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets.
1669
- */
1670
- const offsetListeners = {};
1671
-
1672
- for (const [selector, listener] of Object.entries(baseOffsetListeners)) {
1673
-
1674
- /*
1675
- * Offset listener calls are deferred until traversal is finished, and are called as
1676
- * part of the final `Program:exit` listener. This is necessary because a node might
1677
- * be matched by multiple selectors.
1678
- *
1679
- * Example: Suppose there is an offset listener for `Identifier`, and the user has
1680
- * specified in configuration that `MemberExpression > Identifier` should be ignored.
1681
- * Due to selector specificity rules, the `Identifier` listener will get called first. However,
1682
- * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener
1683
- * should not have been called at all. Without doing extra selector matching, we don't know
1684
- * whether the Identifier matches the `MemberExpression > Identifier` selector until the
1685
- * `MemberExpression > Identifier` listener is called.
1686
- *
1687
- * To avoid this, the `Identifier` listener isn't called until traversal finishes and all
1688
- * ignored nodes are known.
1689
- */
1690
- offsetListeners[selector] = node => listenerCallQueue.push({ listener, node });
1691
- }
1692
-
1693
- // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set.
1694
- const ignoredNodes = new Set();
1695
-
1696
- /**
1697
- * Ignores a node
1698
- * @param {ASTNode} node The node to ignore
1699
- * @returns {void}
1700
- */
1701
- function addToIgnoredNodes(node) {
1702
- ignoredNodes.add(node);
1703
- ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node));
1704
- }
1705
-
1706
- const ignoredNodeListeners = options.ignoredNodes.reduce(
1707
- (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }),
1708
- {}
1709
- );
1710
-
1711
- /*
1712
- * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation
1713
- * at the end.
1714
- *
1715
- * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears
1716
- * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored,
1717
- * so those listeners wouldn't be called anyway.
1718
- */
1719
- return Object.assign(
1720
- offsetListeners,
1721
- ignoredNodeListeners,
1722
- {
1723
- "*:exit"(node) {
1724
-
1725
- // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it.
1726
- if (!KNOWN_NODES.has(node.type)) {
1727
- addToIgnoredNodes(node);
1728
- }
1729
- },
1730
- "Program:exit"() {
1731
-
1732
- // If ignoreComments option is enabled, ignore all comment tokens.
1733
- if (options.ignoreComments) {
1734
- sourceCode.getAllComments()
1735
- .forEach(comment => offsets.ignoreToken(comment));
1736
- }
1737
-
1738
- // Invoke the queued offset listeners for the nodes that aren't ignored.
1739
- for (let i = 0; i < listenerCallQueue.length; i++) {
1740
- const nodeInfo = listenerCallQueue[i];
1741
-
1742
- if (!ignoredNodes.has(nodeInfo.node)) {
1743
- nodeInfo.listener(nodeInfo.node);
1744
- }
1745
- }
1746
-
1747
- // Update the offsets for ignored nodes to prevent their child tokens from being reported.
1748
- ignoredNodes.forEach(ignoreNode);
1749
-
1750
- addParensIndent(sourceCode.ast.tokens);
1751
-
1752
- /*
1753
- * Create a Map from (tokenOrComment) => (precedingToken).
1754
- * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly.
1755
- */
1756
- const precedingTokens = new WeakMap();
1757
-
1758
- for (let i = 0; i < sourceCode.ast.comments.length; i++) {
1759
- const comment = sourceCode.ast.comments[i];
1760
-
1761
- const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
1762
- const hasToken = precedingTokens.has(tokenOrCommentBefore) ? precedingTokens.get(tokenOrCommentBefore) : tokenOrCommentBefore;
1763
-
1764
- precedingTokens.set(comment, hasToken);
1765
- }
1766
-
1767
- for (let i = 1; i < sourceCode.lines.length + 1; i++) {
1768
-
1769
- if (!tokenInfo.firstTokensByLineNumber.has(i)) {
1770
-
1771
- // Don't check indentation on blank lines
1772
- continue;
1773
- }
1774
-
1775
- const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(i);
1776
-
1777
- if (firstTokenOfLine.loc.start.line !== i) {
1778
-
1779
- // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice.
1780
- continue;
1781
- }
1782
-
1783
- if (astUtils.isCommentToken(firstTokenOfLine)) {
1784
- const tokenBefore = precedingTokens.get(firstTokenOfLine);
1785
- const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0];
1786
- const mayAlignWithBefore = tokenBefore && !hasBlankLinesBetween(tokenBefore, firstTokenOfLine);
1787
- const mayAlignWithAfter = tokenAfter && !hasBlankLinesBetween(firstTokenOfLine, tokenAfter);
1788
-
1789
- /*
1790
- * If a comment precedes a line that begins with a semicolon token, align to that token, i.e.
1791
- *
1792
- * let foo
1793
- * // comment
1794
- * ;(async () => {})()
1795
- */
1796
- if (tokenAfter && astUtils.isSemicolonToken(tokenAfter) && !astUtils.isTokenOnSameLine(firstTokenOfLine, tokenAfter)) {
1797
- offsets.setDesiredOffset(firstTokenOfLine, tokenAfter, 0);
1798
- }
1799
-
1800
- // If a comment matches the expected indentation of the token immediately before or after, don't report it.
1801
- if (
1802
- mayAlignWithBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) ||
1803
- mayAlignWithAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter))
1804
- ) {
1805
- continue;
1806
- }
1807
- }
1808
-
1809
- // If the token matches the expected indentation, don't report it.
1810
- if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) {
1811
- continue;
1812
- }
1813
-
1814
- // Otherwise, report the token/comment.
1815
- report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine));
1816
- }
1817
- }
1818
- }
1819
- );
1820
- }
510
+ meta: {
511
+ deprecated: {
512
+ message: "Formatting rules are being moved out of ESLint core.",
513
+ url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
514
+ deprecatedSince: "8.53.0",
515
+ availableUntil: "10.0.0",
516
+ replacedBy: [
517
+ {
518
+ message:
519
+ "ESLint Stylistic now maintains deprecated stylistic core rules.",
520
+ url: "https://eslint.style/guide/migration",
521
+ plugin: {
522
+ name: "@stylistic/eslint-plugin-js",
523
+ url: "https://eslint.style/packages/js",
524
+ },
525
+ rule: {
526
+ name: "indent",
527
+ url: "https://eslint.style/rules/js/indent",
528
+ },
529
+ },
530
+ ],
531
+ },
532
+ type: "layout",
533
+
534
+ docs: {
535
+ description: "Enforce consistent indentation",
536
+ recommended: false,
537
+ url: "https://eslint.org/docs/latest/rules/indent",
538
+ },
539
+
540
+ fixable: "whitespace",
541
+
542
+ schema: [
543
+ {
544
+ oneOf: [
545
+ {
546
+ enum: ["tab"],
547
+ },
548
+ {
549
+ type: "integer",
550
+ minimum: 0,
551
+ },
552
+ ],
553
+ },
554
+ {
555
+ type: "object",
556
+ properties: {
557
+ SwitchCase: {
558
+ type: "integer",
559
+ minimum: 0,
560
+ default: 0,
561
+ },
562
+ VariableDeclarator: {
563
+ oneOf: [
564
+ ELEMENT_LIST_SCHEMA,
565
+ {
566
+ type: "object",
567
+ properties: {
568
+ var: ELEMENT_LIST_SCHEMA,
569
+ let: ELEMENT_LIST_SCHEMA,
570
+ const: ELEMENT_LIST_SCHEMA,
571
+ },
572
+ additionalProperties: false,
573
+ },
574
+ ],
575
+ },
576
+ outerIIFEBody: {
577
+ oneOf: [
578
+ {
579
+ type: "integer",
580
+ minimum: 0,
581
+ },
582
+ {
583
+ enum: ["off"],
584
+ },
585
+ ],
586
+ },
587
+ MemberExpression: {
588
+ oneOf: [
589
+ {
590
+ type: "integer",
591
+ minimum: 0,
592
+ },
593
+ {
594
+ enum: ["off"],
595
+ },
596
+ ],
597
+ },
598
+ FunctionDeclaration: {
599
+ type: "object",
600
+ properties: {
601
+ parameters: ELEMENT_LIST_SCHEMA,
602
+ body: {
603
+ type: "integer",
604
+ minimum: 0,
605
+ },
606
+ },
607
+ additionalProperties: false,
608
+ },
609
+ FunctionExpression: {
610
+ type: "object",
611
+ properties: {
612
+ parameters: ELEMENT_LIST_SCHEMA,
613
+ body: {
614
+ type: "integer",
615
+ minimum: 0,
616
+ },
617
+ },
618
+ additionalProperties: false,
619
+ },
620
+ StaticBlock: {
621
+ type: "object",
622
+ properties: {
623
+ body: {
624
+ type: "integer",
625
+ minimum: 0,
626
+ },
627
+ },
628
+ additionalProperties: false,
629
+ },
630
+ CallExpression: {
631
+ type: "object",
632
+ properties: {
633
+ arguments: ELEMENT_LIST_SCHEMA,
634
+ },
635
+ additionalProperties: false,
636
+ },
637
+ ArrayExpression: ELEMENT_LIST_SCHEMA,
638
+ ObjectExpression: ELEMENT_LIST_SCHEMA,
639
+ ImportDeclaration: ELEMENT_LIST_SCHEMA,
640
+ flatTernaryExpressions: {
641
+ type: "boolean",
642
+ default: false,
643
+ },
644
+ offsetTernaryExpressions: {
645
+ type: "boolean",
646
+ default: false,
647
+ },
648
+ ignoredNodes: {
649
+ type: "array",
650
+ items: {
651
+ type: "string",
652
+ not: {
653
+ pattern: ":exit$",
654
+ },
655
+ },
656
+ },
657
+ ignoreComments: {
658
+ type: "boolean",
659
+ default: false,
660
+ },
661
+ },
662
+ additionalProperties: false,
663
+ },
664
+ ],
665
+ messages: {
666
+ wrongIndentation:
667
+ "Expected indentation of {{expected}} but found {{actual}}.",
668
+ },
669
+ },
670
+
671
+ create(context) {
672
+ const DEFAULT_VARIABLE_INDENT = 1;
673
+ const DEFAULT_PARAMETER_INDENT = 1;
674
+ const DEFAULT_FUNCTION_BODY_INDENT = 1;
675
+
676
+ let indentType = "space";
677
+ let indentSize = 4;
678
+ const options = {
679
+ SwitchCase: 0,
680
+ VariableDeclarator: {
681
+ var: DEFAULT_VARIABLE_INDENT,
682
+ let: DEFAULT_VARIABLE_INDENT,
683
+ const: DEFAULT_VARIABLE_INDENT,
684
+ },
685
+ outerIIFEBody: 1,
686
+ FunctionDeclaration: {
687
+ parameters: DEFAULT_PARAMETER_INDENT,
688
+ body: DEFAULT_FUNCTION_BODY_INDENT,
689
+ },
690
+ FunctionExpression: {
691
+ parameters: DEFAULT_PARAMETER_INDENT,
692
+ body: DEFAULT_FUNCTION_BODY_INDENT,
693
+ },
694
+ StaticBlock: {
695
+ body: DEFAULT_FUNCTION_BODY_INDENT,
696
+ },
697
+ CallExpression: {
698
+ arguments: DEFAULT_PARAMETER_INDENT,
699
+ },
700
+ MemberExpression: 1,
701
+ ArrayExpression: 1,
702
+ ObjectExpression: 1,
703
+ ImportDeclaration: 1,
704
+ flatTernaryExpressions: false,
705
+ ignoredNodes: [],
706
+ ignoreComments: false,
707
+ };
708
+
709
+ if (context.options.length) {
710
+ if (context.options[0] === "tab") {
711
+ indentSize = 1;
712
+ indentType = "tab";
713
+ } else {
714
+ indentSize = context.options[0];
715
+ indentType = "space";
716
+ }
717
+
718
+ if (context.options[1]) {
719
+ Object.assign(options, context.options[1]);
720
+
721
+ if (
722
+ typeof options.VariableDeclarator === "number" ||
723
+ options.VariableDeclarator === "first"
724
+ ) {
725
+ options.VariableDeclarator = {
726
+ var: options.VariableDeclarator,
727
+ let: options.VariableDeclarator,
728
+ const: options.VariableDeclarator,
729
+ };
730
+ }
731
+ }
732
+ }
733
+
734
+ const sourceCode = context.sourceCode;
735
+ const tokenInfo = new TokenInfo(sourceCode);
736
+ const offsets = new OffsetStorage(
737
+ tokenInfo,
738
+ indentSize,
739
+ indentType === "space" ? " " : "\t",
740
+ sourceCode.text.length,
741
+ );
742
+ const parameterParens = new WeakSet();
743
+
744
+ /**
745
+ * Creates an error message for a line, given the expected/actual indentation.
746
+ * @param {int} expectedAmount The expected amount of indentation characters for this line
747
+ * @param {int} actualSpaces The actual number of indentation spaces that were found on this line
748
+ * @param {int} actualTabs The actual number of indentation tabs that were found on this line
749
+ * @returns {string} An error message for this line
750
+ */
751
+ function createErrorMessageData(
752
+ expectedAmount,
753
+ actualSpaces,
754
+ actualTabs,
755
+ ) {
756
+ const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs"
757
+ const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space"
758
+ const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs"
759
+ let foundStatement;
760
+
761
+ if (actualSpaces > 0) {
762
+ /*
763
+ * Abbreviate the message if the expected indentation is also spaces.
764
+ * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
765
+ */
766
+ foundStatement =
767
+ indentType === "space"
768
+ ? actualSpaces
769
+ : `${actualSpaces} ${foundSpacesWord}`;
770
+ } else if (actualTabs > 0) {
771
+ foundStatement =
772
+ indentType === "tab"
773
+ ? actualTabs
774
+ : `${actualTabs} ${foundTabsWord}`;
775
+ } else {
776
+ foundStatement = "0";
777
+ }
778
+ return {
779
+ expected: expectedStatement,
780
+ actual: foundStatement,
781
+ };
782
+ }
783
+
784
+ /**
785
+ * Reports a given indent violation
786
+ * @param {Token} token Token violating the indent rule
787
+ * @param {string} neededIndent Expected indentation string
788
+ * @returns {void}
789
+ */
790
+ function report(token, neededIndent) {
791
+ const actualIndent = Array.from(tokenInfo.getTokenIndent(token));
792
+ const numSpaces = actualIndent.filter(char => char === " ").length;
793
+ const numTabs = actualIndent.filter(char => char === "\t").length;
794
+
795
+ context.report({
796
+ node: token,
797
+ messageId: "wrongIndentation",
798
+ data: createErrorMessageData(
799
+ neededIndent.length,
800
+ numSpaces,
801
+ numTabs,
802
+ ),
803
+ loc: {
804
+ start: { line: token.loc.start.line, column: 0 },
805
+ end: {
806
+ line: token.loc.start.line,
807
+ column: token.loc.start.column,
808
+ },
809
+ },
810
+ fix(fixer) {
811
+ const range = [
812
+ token.range[0] - token.loc.start.column,
813
+ token.range[0],
814
+ ];
815
+ const newText = neededIndent;
816
+
817
+ return fixer.replaceTextRange(range, newText);
818
+ },
819
+ });
820
+ }
821
+
822
+ /**
823
+ * Checks if a token's indentation is correct
824
+ * @param {Token} token Token to examine
825
+ * @param {string} desiredIndent Desired indentation of the string
826
+ * @returns {boolean} `true` if the token's indentation is correct
827
+ */
828
+ function validateTokenIndent(token, desiredIndent) {
829
+ const indentation = tokenInfo.getTokenIndent(token);
830
+
831
+ return (
832
+ indentation === desiredIndent ||
833
+ // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
834
+ (indentation.includes(" ") && indentation.includes("\t"))
835
+ );
836
+ }
837
+
838
+ /**
839
+ * Check to see if the node is a file level IIFE
840
+ * @param {ASTNode} node The function node to check.
841
+ * @returns {boolean} True if the node is the outer IIFE
842
+ */
843
+ function isOuterIIFE(node) {
844
+ /*
845
+ * Verify that the node is an IIFE
846
+ */
847
+ if (
848
+ !node.parent ||
849
+ node.parent.type !== "CallExpression" ||
850
+ node.parent.callee !== node
851
+ ) {
852
+ return false;
853
+ }
854
+
855
+ /*
856
+ * Navigate legal ancestors to determine whether this IIFE is outer.
857
+ * A "legal ancestor" is an expression or statement that causes the function to get executed immediately.
858
+ * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator.
859
+ */
860
+ let statement = node.parent && node.parent.parent;
861
+
862
+ while (
863
+ (statement.type === "UnaryExpression" &&
864
+ ["!", "~", "+", "-"].includes(statement.operator)) ||
865
+ statement.type === "AssignmentExpression" ||
866
+ statement.type === "LogicalExpression" ||
867
+ statement.type === "SequenceExpression" ||
868
+ statement.type === "VariableDeclarator"
869
+ ) {
870
+ statement = statement.parent;
871
+ }
872
+
873
+ return (
874
+ (statement.type === "ExpressionStatement" ||
875
+ statement.type === "VariableDeclaration") &&
876
+ statement.parent.type === "Program"
877
+ );
878
+ }
879
+
880
+ /**
881
+ * Counts the number of linebreaks that follow the last non-whitespace character in a string
882
+ * @param {string} string The string to check
883
+ * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character,
884
+ * or the total number of linebreaks if the string is all whitespace.
885
+ */
886
+ function countTrailingLinebreaks(string) {
887
+ const trailingWhitespace = string.match(/\s*$/u)[0];
888
+ const linebreakMatches = trailingWhitespace.match(
889
+ astUtils.createGlobalLinebreakMatcher(),
890
+ );
891
+
892
+ return linebreakMatches === null ? 0 : linebreakMatches.length;
893
+ }
894
+
895
+ /**
896
+ * Check indentation for lists of elements (arrays, objects, function params)
897
+ * @param {ASTNode[]} elements List of elements that should be offset
898
+ * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '['
899
+ * @param {Token} endToken The end token of the list, e.g. ']'
900
+ * @param {number|string} offset The amount that the elements should be offset
901
+ * @returns {void}
902
+ */
903
+ function addElementListIndent(elements, startToken, endToken, offset) {
904
+ /**
905
+ * Gets the first token of a given element, including surrounding parentheses.
906
+ * @param {ASTNode} element A node in the `elements` list
907
+ * @returns {Token} The first token of this element
908
+ */
909
+ function getFirstToken(element) {
910
+ let token = sourceCode.getTokenBefore(element);
911
+
912
+ while (
913
+ astUtils.isOpeningParenToken(token) &&
914
+ token !== startToken
915
+ ) {
916
+ token = sourceCode.getTokenBefore(token);
917
+ }
918
+ return sourceCode.getTokenAfter(token);
919
+ }
920
+
921
+ // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden)
922
+ offsets.setDesiredOffsets(
923
+ [startToken.range[1], endToken.range[0]],
924
+ startToken,
925
+ typeof offset === "number" ? offset : 1,
926
+ );
927
+ offsets.setDesiredOffset(endToken, startToken, 0);
928
+
929
+ // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level.
930
+ if (offset === "first" && elements.length && !elements[0]) {
931
+ return;
932
+ }
933
+ elements.forEach((element, index) => {
934
+ if (!element) {
935
+ // Skip holes in arrays
936
+ return;
937
+ }
938
+ if (offset === "off") {
939
+ // Ignore the first token of every element if the "off" option is used
940
+ offsets.ignoreToken(getFirstToken(element));
941
+ }
942
+
943
+ // Offset the following elements correctly relative to the first element
944
+ if (index === 0) {
945
+ return;
946
+ }
947
+ if (
948
+ offset === "first" &&
949
+ tokenInfo.isFirstTokenOfLine(getFirstToken(element))
950
+ ) {
951
+ offsets.matchOffsetOf(
952
+ getFirstToken(elements[0]),
953
+ getFirstToken(element),
954
+ );
955
+ } else {
956
+ const previousElement = elements[index - 1];
957
+ const firstTokenOfPreviousElement =
958
+ previousElement && getFirstToken(previousElement);
959
+ const previousElementLastToken =
960
+ previousElement &&
961
+ sourceCode.getLastToken(previousElement);
962
+
963
+ if (
964
+ previousElement &&
965
+ previousElementLastToken.loc.end.line -
966
+ countTrailingLinebreaks(
967
+ previousElementLastToken.value,
968
+ ) >
969
+ startToken.loc.end.line
970
+ ) {
971
+ offsets.setDesiredOffsets(
972
+ [previousElement.range[1], element.range[1]],
973
+ firstTokenOfPreviousElement,
974
+ 0,
975
+ );
976
+ }
977
+ }
978
+ });
979
+ }
980
+
981
+ /**
982
+ * Check and decide whether to check for indentation for blockless nodes
983
+ * Scenarios are for or while statements without braces around them
984
+ * @param {ASTNode} node node to examine
985
+ * @returns {void}
986
+ */
987
+ function addBlocklessNodeIndent(node) {
988
+ if (node.type !== "BlockStatement") {
989
+ const lastParentToken = sourceCode.getTokenBefore(
990
+ node,
991
+ astUtils.isNotOpeningParenToken,
992
+ );
993
+
994
+ let firstBodyToken = sourceCode.getFirstToken(node);
995
+ let lastBodyToken = sourceCode.getLastToken(node);
996
+
997
+ while (
998
+ astUtils.isOpeningParenToken(
999
+ sourceCode.getTokenBefore(firstBodyToken),
1000
+ ) &&
1001
+ astUtils.isClosingParenToken(
1002
+ sourceCode.getTokenAfter(lastBodyToken),
1003
+ )
1004
+ ) {
1005
+ firstBodyToken = sourceCode.getTokenBefore(firstBodyToken);
1006
+ lastBodyToken = sourceCode.getTokenAfter(lastBodyToken);
1007
+ }
1008
+
1009
+ offsets.setDesiredOffsets(
1010
+ [firstBodyToken.range[0], lastBodyToken.range[1]],
1011
+ lastParentToken,
1012
+ 1,
1013
+ );
1014
+ }
1015
+ }
1016
+
1017
+ /**
1018
+ * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`)
1019
+ * @param {ASTNode} node A CallExpression or NewExpression node
1020
+ * @returns {void}
1021
+ */
1022
+ function addFunctionCallIndent(node) {
1023
+ let openingParen;
1024
+
1025
+ if (node.arguments.length) {
1026
+ openingParen = sourceCode.getFirstTokenBetween(
1027
+ node.callee,
1028
+ node.arguments[0],
1029
+ astUtils.isOpeningParenToken,
1030
+ );
1031
+ } else {
1032
+ openingParen = sourceCode.getLastToken(node, 1);
1033
+ }
1034
+ const closingParen = sourceCode.getLastToken(node);
1035
+
1036
+ parameterParens.add(openingParen);
1037
+ parameterParens.add(closingParen);
1038
+
1039
+ /*
1040
+ * If `?.` token exists, set desired offset for that.
1041
+ * This logic is copied from `MemberExpression`'s.
1042
+ */
1043
+ if (node.optional) {
1044
+ const dotToken = sourceCode.getTokenAfter(
1045
+ node.callee,
1046
+ astUtils.isQuestionDotToken,
1047
+ );
1048
+ const calleeParenCount = sourceCode.getTokensBetween(
1049
+ node.callee,
1050
+ dotToken,
1051
+ { filter: astUtils.isClosingParenToken },
1052
+ ).length;
1053
+ const firstTokenOfCallee = calleeParenCount
1054
+ ? sourceCode.getTokenBefore(node.callee, {
1055
+ skip: calleeParenCount - 1,
1056
+ })
1057
+ : sourceCode.getFirstToken(node.callee);
1058
+ const lastTokenOfCallee = sourceCode.getTokenBefore(dotToken);
1059
+ const offsetBase =
1060
+ lastTokenOfCallee.loc.end.line ===
1061
+ openingParen.loc.start.line
1062
+ ? lastTokenOfCallee
1063
+ : firstTokenOfCallee;
1064
+
1065
+ offsets.setDesiredOffset(dotToken, offsetBase, 1);
1066
+ }
1067
+
1068
+ const offsetAfterToken =
1069
+ node.callee.type === "TaggedTemplateExpression"
1070
+ ? sourceCode.getFirstToken(node.callee.quasi)
1071
+ : openingParen;
1072
+ const offsetToken = sourceCode.getTokenBefore(offsetAfterToken);
1073
+
1074
+ offsets.setDesiredOffset(openingParen, offsetToken, 0);
1075
+
1076
+ addElementListIndent(
1077
+ node.arguments,
1078
+ openingParen,
1079
+ closingParen,
1080
+ options.CallExpression.arguments,
1081
+ );
1082
+ }
1083
+
1084
+ /**
1085
+ * Checks the indentation of parenthesized values, given a list of tokens in a program
1086
+ * @param {Token[]} tokens A list of tokens
1087
+ * @returns {void}
1088
+ */
1089
+ function addParensIndent(tokens) {
1090
+ const parenStack = [];
1091
+ const parenPairs = [];
1092
+
1093
+ for (let i = 0; i < tokens.length; i++) {
1094
+ const nextToken = tokens[i];
1095
+
1096
+ if (astUtils.isOpeningParenToken(nextToken)) {
1097
+ parenStack.push(nextToken);
1098
+ } else if (astUtils.isClosingParenToken(nextToken)) {
1099
+ parenPairs.push({
1100
+ left: parenStack.pop(),
1101
+ right: nextToken,
1102
+ });
1103
+ }
1104
+ }
1105
+
1106
+ for (let i = parenPairs.length - 1; i >= 0; i--) {
1107
+ const leftParen = parenPairs[i].left;
1108
+ const rightParen = parenPairs[i].right;
1109
+
1110
+ // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.
1111
+ if (
1112
+ !parameterParens.has(leftParen) &&
1113
+ !parameterParens.has(rightParen)
1114
+ ) {
1115
+ const parenthesizedTokens = new Set(
1116
+ sourceCode.getTokensBetween(leftParen, rightParen),
1117
+ );
1118
+
1119
+ parenthesizedTokens.forEach(token => {
1120
+ if (
1121
+ !parenthesizedTokens.has(
1122
+ offsets.getFirstDependency(token),
1123
+ )
1124
+ ) {
1125
+ offsets.setDesiredOffset(token, leftParen, 1);
1126
+ }
1127
+ });
1128
+ }
1129
+
1130
+ offsets.setDesiredOffset(rightParen, leftParen, 0);
1131
+ }
1132
+ }
1133
+
1134
+ /**
1135
+ * Ignore all tokens within an unknown node whose offset do not depend
1136
+ * on another token's offset within the unknown node
1137
+ * @param {ASTNode} node Unknown Node
1138
+ * @returns {void}
1139
+ */
1140
+ function ignoreNode(node) {
1141
+ const unknownNodeTokens = new Set(
1142
+ sourceCode.getTokens(node, { includeComments: true }),
1143
+ );
1144
+
1145
+ unknownNodeTokens.forEach(token => {
1146
+ if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) {
1147
+ const firstTokenOfLine =
1148
+ tokenInfo.getFirstTokenOfLine(token);
1149
+
1150
+ if (token === firstTokenOfLine) {
1151
+ offsets.ignoreToken(token);
1152
+ } else {
1153
+ offsets.setDesiredOffset(token, firstTokenOfLine, 0);
1154
+ }
1155
+ }
1156
+ });
1157
+ }
1158
+
1159
+ /**
1160
+ * Check whether the given token is on the first line of a statement.
1161
+ * @param {Token} token The token to check.
1162
+ * @param {ASTNode} leafNode The expression node that the token belongs directly.
1163
+ * @returns {boolean} `true` if the token is on the first line of a statement.
1164
+ */
1165
+ function isOnFirstLineOfStatement(token, leafNode) {
1166
+ let node = leafNode;
1167
+
1168
+ while (
1169
+ node.parent &&
1170
+ !node.parent.type.endsWith("Statement") &&
1171
+ !node.parent.type.endsWith("Declaration")
1172
+ ) {
1173
+ node = node.parent;
1174
+ }
1175
+ node = node.parent;
1176
+
1177
+ return !node || node.loc.start.line === token.loc.start.line;
1178
+ }
1179
+
1180
+ /**
1181
+ * Check whether there are any blank (whitespace-only) lines between
1182
+ * two tokens on separate lines.
1183
+ * @param {Token} firstToken The first token.
1184
+ * @param {Token} secondToken The second token.
1185
+ * @returns {boolean} `true` if the tokens are on separate lines and
1186
+ * there exists a blank line between them, `false` otherwise.
1187
+ */
1188
+ function hasBlankLinesBetween(firstToken, secondToken) {
1189
+ const firstTokenLine = firstToken.loc.end.line;
1190
+ const secondTokenLine = secondToken.loc.start.line;
1191
+
1192
+ if (
1193
+ firstTokenLine === secondTokenLine ||
1194
+ firstTokenLine === secondTokenLine - 1
1195
+ ) {
1196
+ return false;
1197
+ }
1198
+
1199
+ for (
1200
+ let line = firstTokenLine + 1;
1201
+ line < secondTokenLine;
1202
+ ++line
1203
+ ) {
1204
+ if (!tokenInfo.firstTokensByLineNumber.has(line)) {
1205
+ return true;
1206
+ }
1207
+ }
1208
+
1209
+ return false;
1210
+ }
1211
+
1212
+ const ignoredNodeFirstTokens = new Set();
1213
+
1214
+ const baseOffsetListeners = {
1215
+ "ArrayExpression, ArrayPattern"(node) {
1216
+ const openingBracket = sourceCode.getFirstToken(node);
1217
+ const closingBracket = sourceCode.getTokenAfter(
1218
+ [...node.elements].reverse().find(_ => _) || openingBracket,
1219
+ astUtils.isClosingBracketToken,
1220
+ );
1221
+
1222
+ addElementListIndent(
1223
+ node.elements,
1224
+ openingBracket,
1225
+ closingBracket,
1226
+ options.ArrayExpression,
1227
+ );
1228
+ },
1229
+
1230
+ "ObjectExpression, ObjectPattern"(node) {
1231
+ const openingCurly = sourceCode.getFirstToken(node);
1232
+ const closingCurly = sourceCode.getTokenAfter(
1233
+ node.properties.length
1234
+ ? node.properties.at(-1)
1235
+ : openingCurly,
1236
+ astUtils.isClosingBraceToken,
1237
+ );
1238
+
1239
+ addElementListIndent(
1240
+ node.properties,
1241
+ openingCurly,
1242
+ closingCurly,
1243
+ options.ObjectExpression,
1244
+ );
1245
+ },
1246
+
1247
+ ArrowFunctionExpression(node) {
1248
+ const maybeOpeningParen = sourceCode.getFirstToken(node, {
1249
+ skip: node.async ? 1 : 0,
1250
+ });
1251
+
1252
+ if (astUtils.isOpeningParenToken(maybeOpeningParen)) {
1253
+ const openingParen = maybeOpeningParen;
1254
+ const closingParen = sourceCode.getTokenBefore(
1255
+ node.body,
1256
+ astUtils.isClosingParenToken,
1257
+ );
1258
+
1259
+ parameterParens.add(openingParen);
1260
+ parameterParens.add(closingParen);
1261
+ addElementListIndent(
1262
+ node.params,
1263
+ openingParen,
1264
+ closingParen,
1265
+ options.FunctionExpression.parameters,
1266
+ );
1267
+ }
1268
+
1269
+ addBlocklessNodeIndent(node.body);
1270
+ },
1271
+
1272
+ AssignmentExpression(node) {
1273
+ const operator = sourceCode.getFirstTokenBetween(
1274
+ node.left,
1275
+ node.right,
1276
+ token => token.value === node.operator,
1277
+ );
1278
+
1279
+ offsets.setDesiredOffsets(
1280
+ [operator.range[0], node.range[1]],
1281
+ sourceCode.getLastToken(node.left),
1282
+ 1,
1283
+ );
1284
+ offsets.ignoreToken(operator);
1285
+ offsets.ignoreToken(sourceCode.getTokenAfter(operator));
1286
+ },
1287
+
1288
+ "BinaryExpression, LogicalExpression"(node) {
1289
+ const operator = sourceCode.getFirstTokenBetween(
1290
+ node.left,
1291
+ node.right,
1292
+ token => token.value === node.operator,
1293
+ );
1294
+
1295
+ /*
1296
+ * For backwards compatibility, don't check BinaryExpression indents, e.g.
1297
+ * var foo = bar &&
1298
+ * baz;
1299
+ */
1300
+
1301
+ const tokenAfterOperator = sourceCode.getTokenAfter(operator);
1302
+
1303
+ offsets.ignoreToken(operator);
1304
+ offsets.ignoreToken(tokenAfterOperator);
1305
+ offsets.setDesiredOffset(tokenAfterOperator, operator, 0);
1306
+ },
1307
+
1308
+ "BlockStatement, ClassBody"(node) {
1309
+ let blockIndentLevel;
1310
+
1311
+ if (node.parent && isOuterIIFE(node.parent)) {
1312
+ blockIndentLevel = options.outerIIFEBody;
1313
+ } else if (
1314
+ node.parent &&
1315
+ (node.parent.type === "FunctionExpression" ||
1316
+ node.parent.type === "ArrowFunctionExpression")
1317
+ ) {
1318
+ blockIndentLevel = options.FunctionExpression.body;
1319
+ } else if (
1320
+ node.parent &&
1321
+ node.parent.type === "FunctionDeclaration"
1322
+ ) {
1323
+ blockIndentLevel = options.FunctionDeclaration.body;
1324
+ } else {
1325
+ blockIndentLevel = 1;
1326
+ }
1327
+
1328
+ /*
1329
+ * For blocks that aren't lone statements, ensure that the opening curly brace
1330
+ * is aligned with the parent.
1331
+ */
1332
+ if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
1333
+ offsets.setDesiredOffset(
1334
+ sourceCode.getFirstToken(node),
1335
+ sourceCode.getFirstToken(node.parent),
1336
+ 0,
1337
+ );
1338
+ }
1339
+
1340
+ addElementListIndent(
1341
+ node.body,
1342
+ sourceCode.getFirstToken(node),
1343
+ sourceCode.getLastToken(node),
1344
+ blockIndentLevel,
1345
+ );
1346
+ },
1347
+
1348
+ CallExpression: addFunctionCallIndent,
1349
+
1350
+ "ClassDeclaration[superClass], ClassExpression[superClass]"(node) {
1351
+ const classToken = sourceCode.getFirstToken(node);
1352
+ const extendsToken = sourceCode.getTokenBefore(
1353
+ node.superClass,
1354
+ astUtils.isNotOpeningParenToken,
1355
+ );
1356
+
1357
+ offsets.setDesiredOffsets(
1358
+ [extendsToken.range[0], node.body.range[0]],
1359
+ classToken,
1360
+ 1,
1361
+ );
1362
+ },
1363
+
1364
+ ConditionalExpression(node) {
1365
+ const firstToken = sourceCode.getFirstToken(node);
1366
+
1367
+ // `flatTernaryExpressions` option is for the following style:
1368
+ // var a =
1369
+ // foo > 0 ? bar :
1370
+ // foo < 0 ? baz :
1371
+ // /*else*/ qiz ;
1372
+ if (
1373
+ !options.flatTernaryExpressions ||
1374
+ !astUtils.isTokenOnSameLine(node.test, node.consequent) ||
1375
+ isOnFirstLineOfStatement(firstToken, node)
1376
+ ) {
1377
+ const questionMarkToken = sourceCode.getFirstTokenBetween(
1378
+ node.test,
1379
+ node.consequent,
1380
+ token =>
1381
+ token.type === "Punctuator" && token.value === "?",
1382
+ );
1383
+ const colonToken = sourceCode.getFirstTokenBetween(
1384
+ node.consequent,
1385
+ node.alternate,
1386
+ token =>
1387
+ token.type === "Punctuator" && token.value === ":",
1388
+ );
1389
+
1390
+ const firstConsequentToken =
1391
+ sourceCode.getTokenAfter(questionMarkToken);
1392
+ const lastConsequentToken =
1393
+ sourceCode.getTokenBefore(colonToken);
1394
+ const firstAlternateToken =
1395
+ sourceCode.getTokenAfter(colonToken);
1396
+
1397
+ offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
1398
+ offsets.setDesiredOffset(colonToken, firstToken, 1);
1399
+
1400
+ offsets.setDesiredOffset(
1401
+ firstConsequentToken,
1402
+ firstToken,
1403
+ firstConsequentToken.type === "Punctuator" &&
1404
+ options.offsetTernaryExpressions
1405
+ ? 2
1406
+ : 1,
1407
+ );
1408
+
1409
+ /*
1410
+ * The alternate and the consequent should usually have the same indentation.
1411
+ * If they share part of a line, align the alternate against the first token of the consequent.
1412
+ * This allows the alternate to be indented correctly in cases like this:
1413
+ * foo ? (
1414
+ * bar
1415
+ * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo`
1416
+ * baz // as a result, `baz` is offset by 1 rather than 2
1417
+ * )
1418
+ */
1419
+ if (
1420
+ lastConsequentToken.loc.end.line ===
1421
+ firstAlternateToken.loc.start.line
1422
+ ) {
1423
+ offsets.setDesiredOffset(
1424
+ firstAlternateToken,
1425
+ firstConsequentToken,
1426
+ 0,
1427
+ );
1428
+ } else {
1429
+ /**
1430
+ * If the alternate and consequent do not share part of a line, offset the alternate from the first
1431
+ * token of the conditional expression. For example:
1432
+ * foo ? bar
1433
+ * : baz
1434
+ *
1435
+ * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
1436
+ * having no expected indentation.
1437
+ */
1438
+ offsets.setDesiredOffset(
1439
+ firstAlternateToken,
1440
+ firstToken,
1441
+ firstAlternateToken.type === "Punctuator" &&
1442
+ options.offsetTernaryExpressions
1443
+ ? 2
1444
+ : 1,
1445
+ );
1446
+ }
1447
+ }
1448
+ },
1449
+
1450
+ "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement, WithStatement":
1451
+ node => addBlocklessNodeIndent(node.body),
1452
+
1453
+ ExportNamedDeclaration(node) {
1454
+ if (node.declaration === null) {
1455
+ const closingCurly = sourceCode.getLastToken(
1456
+ node,
1457
+ astUtils.isClosingBraceToken,
1458
+ );
1459
+
1460
+ // Indent the specifiers in `export {foo, bar, baz}`
1461
+ addElementListIndent(
1462
+ node.specifiers,
1463
+ sourceCode.getFirstToken(node, { skip: 1 }),
1464
+ closingCurly,
1465
+ 1,
1466
+ );
1467
+
1468
+ if (node.source) {
1469
+ // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'`
1470
+ offsets.setDesiredOffsets(
1471
+ [closingCurly.range[1], node.range[1]],
1472
+ sourceCode.getFirstToken(node),
1473
+ 1,
1474
+ );
1475
+ }
1476
+ }
1477
+ },
1478
+
1479
+ ForStatement(node) {
1480
+ const forOpeningParen = sourceCode.getFirstToken(node, 1);
1481
+
1482
+ if (node.init) {
1483
+ offsets.setDesiredOffsets(
1484
+ node.init.range,
1485
+ forOpeningParen,
1486
+ 1,
1487
+ );
1488
+ }
1489
+ if (node.test) {
1490
+ offsets.setDesiredOffsets(
1491
+ node.test.range,
1492
+ forOpeningParen,
1493
+ 1,
1494
+ );
1495
+ }
1496
+ if (node.update) {
1497
+ offsets.setDesiredOffsets(
1498
+ node.update.range,
1499
+ forOpeningParen,
1500
+ 1,
1501
+ );
1502
+ }
1503
+ addBlocklessNodeIndent(node.body);
1504
+ },
1505
+
1506
+ "FunctionDeclaration, FunctionExpression"(node) {
1507
+ const closingParen = sourceCode.getTokenBefore(node.body);
1508
+ const openingParen = sourceCode.getTokenBefore(
1509
+ node.params.length ? node.params[0] : closingParen,
1510
+ );
1511
+
1512
+ parameterParens.add(openingParen);
1513
+ parameterParens.add(closingParen);
1514
+ addElementListIndent(
1515
+ node.params,
1516
+ openingParen,
1517
+ closingParen,
1518
+ options[node.type].parameters,
1519
+ );
1520
+ },
1521
+
1522
+ IfStatement(node) {
1523
+ addBlocklessNodeIndent(node.consequent);
1524
+ if (node.alternate) {
1525
+ addBlocklessNodeIndent(node.alternate);
1526
+ }
1527
+ },
1528
+
1529
+ /*
1530
+ * For blockless nodes with semicolon-first style, don't indent the semicolon.
1531
+ * e.g.
1532
+ * if (foo)
1533
+ * bar()
1534
+ * ; [1, 2, 3].map(foo)
1535
+ *
1536
+ * Traversal into the node sets indentation of the semicolon, so we need to override it on exit.
1537
+ */
1538
+ ":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement, WithStatement):exit"(
1539
+ node,
1540
+ ) {
1541
+ let nodesToCheck;
1542
+
1543
+ if (node.type === "IfStatement") {
1544
+ nodesToCheck = [node.consequent];
1545
+ if (node.alternate) {
1546
+ nodesToCheck.push(node.alternate);
1547
+ }
1548
+ } else {
1549
+ nodesToCheck = [node.body];
1550
+ }
1551
+
1552
+ for (const nodeToCheck of nodesToCheck) {
1553
+ const lastToken = sourceCode.getLastToken(nodeToCheck);
1554
+
1555
+ if (astUtils.isSemicolonToken(lastToken)) {
1556
+ const tokenBeforeLast =
1557
+ sourceCode.getTokenBefore(lastToken);
1558
+ const tokenAfterLast =
1559
+ sourceCode.getTokenAfter(lastToken);
1560
+
1561
+ // override indentation of `;` only if its line looks like a semicolon-first style line
1562
+ if (
1563
+ !astUtils.isTokenOnSameLine(
1564
+ tokenBeforeLast,
1565
+ lastToken,
1566
+ ) &&
1567
+ tokenAfterLast &&
1568
+ astUtils.isTokenOnSameLine(
1569
+ lastToken,
1570
+ tokenAfterLast,
1571
+ )
1572
+ ) {
1573
+ offsets.setDesiredOffset(
1574
+ lastToken,
1575
+ sourceCode.getFirstToken(node),
1576
+ 0,
1577
+ );
1578
+ }
1579
+ }
1580
+ }
1581
+ },
1582
+
1583
+ ImportDeclaration(node) {
1584
+ if (
1585
+ node.specifiers.some(
1586
+ specifier => specifier.type === "ImportSpecifier",
1587
+ )
1588
+ ) {
1589
+ const openingCurly = sourceCode.getFirstToken(
1590
+ node,
1591
+ astUtils.isOpeningBraceToken,
1592
+ );
1593
+ const closingCurly = sourceCode.getLastToken(
1594
+ node,
1595
+ astUtils.isClosingBraceToken,
1596
+ );
1597
+
1598
+ addElementListIndent(
1599
+ node.specifiers.filter(
1600
+ specifier => specifier.type === "ImportSpecifier",
1601
+ ),
1602
+ openingCurly,
1603
+ closingCurly,
1604
+ options.ImportDeclaration,
1605
+ );
1606
+ }
1607
+
1608
+ const fromToken = sourceCode.getLastToken(
1609
+ node,
1610
+ token =>
1611
+ token.type === "Identifier" && token.value === "from",
1612
+ );
1613
+ const sourceToken = sourceCode.getLastToken(
1614
+ node,
1615
+ token => token.type === "String",
1616
+ );
1617
+ const semiToken = sourceCode.getLastToken(
1618
+ node,
1619
+ token => token.type === "Punctuator" && token.value === ";",
1620
+ );
1621
+
1622
+ if (fromToken) {
1623
+ const end =
1624
+ semiToken && semiToken.range[1] === sourceToken.range[1]
1625
+ ? node.range[1]
1626
+ : sourceToken.range[1];
1627
+
1628
+ offsets.setDesiredOffsets(
1629
+ [fromToken.range[0], end],
1630
+ sourceCode.getFirstToken(node),
1631
+ 1,
1632
+ );
1633
+ }
1634
+ },
1635
+
1636
+ ImportExpression(node) {
1637
+ const openingParen = sourceCode.getFirstToken(node, 1);
1638
+ const closingParen = sourceCode.getLastToken(node);
1639
+
1640
+ parameterParens.add(openingParen);
1641
+ parameterParens.add(closingParen);
1642
+ offsets.setDesiredOffset(
1643
+ openingParen,
1644
+ sourceCode.getTokenBefore(openingParen),
1645
+ 0,
1646
+ );
1647
+
1648
+ addElementListIndent(
1649
+ [node.source],
1650
+ openingParen,
1651
+ closingParen,
1652
+ options.CallExpression.arguments,
1653
+ );
1654
+ },
1655
+
1656
+ "MemberExpression, JSXMemberExpression, MetaProperty"(node) {
1657
+ const object =
1658
+ node.type === "MetaProperty" ? node.meta : node.object;
1659
+ const firstNonObjectToken = sourceCode.getFirstTokenBetween(
1660
+ object,
1661
+ node.property,
1662
+ astUtils.isNotClosingParenToken,
1663
+ );
1664
+ const secondNonObjectToken =
1665
+ sourceCode.getTokenAfter(firstNonObjectToken);
1666
+
1667
+ const objectParenCount = sourceCode.getTokensBetween(
1668
+ object,
1669
+ node.property,
1670
+ { filter: astUtils.isClosingParenToken },
1671
+ ).length;
1672
+ const firstObjectToken = objectParenCount
1673
+ ? sourceCode.getTokenBefore(object, {
1674
+ skip: objectParenCount - 1,
1675
+ })
1676
+ : sourceCode.getFirstToken(object);
1677
+ const lastObjectToken =
1678
+ sourceCode.getTokenBefore(firstNonObjectToken);
1679
+ const firstPropertyToken = node.computed
1680
+ ? firstNonObjectToken
1681
+ : secondNonObjectToken;
1682
+
1683
+ if (node.computed) {
1684
+ // For computed MemberExpressions, match the closing bracket with the opening bracket.
1685
+ offsets.setDesiredOffset(
1686
+ sourceCode.getLastToken(node),
1687
+ firstNonObjectToken,
1688
+ 0,
1689
+ );
1690
+ offsets.setDesiredOffsets(
1691
+ node.property.range,
1692
+ firstNonObjectToken,
1693
+ 1,
1694
+ );
1695
+ }
1696
+
1697
+ /*
1698
+ * If the object ends on the same line that the property starts, match against the last token
1699
+ * of the object, to ensure that the MemberExpression is not indented.
1700
+ *
1701
+ * Otherwise, match against the first token of the object, e.g.
1702
+ * foo
1703
+ * .bar
1704
+ * .baz // <-- offset by 1 from `foo`
1705
+ */
1706
+ const offsetBase =
1707
+ lastObjectToken.loc.end.line ===
1708
+ firstPropertyToken.loc.start.line
1709
+ ? lastObjectToken
1710
+ : firstObjectToken;
1711
+
1712
+ if (typeof options.MemberExpression === "number") {
1713
+ // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object.
1714
+ offsets.setDesiredOffset(
1715
+ firstNonObjectToken,
1716
+ offsetBase,
1717
+ options.MemberExpression,
1718
+ );
1719
+
1720
+ /*
1721
+ * For computed MemberExpressions, match the first token of the property against the opening bracket.
1722
+ * Otherwise, match the first token of the property against the object.
1723
+ */
1724
+ offsets.setDesiredOffset(
1725
+ secondNonObjectToken,
1726
+ node.computed ? firstNonObjectToken : offsetBase,
1727
+ options.MemberExpression,
1728
+ );
1729
+ } else {
1730
+ // If the MemberExpression option is off, ignore the dot and the first token of the property.
1731
+ offsets.ignoreToken(firstNonObjectToken);
1732
+ offsets.ignoreToken(secondNonObjectToken);
1733
+
1734
+ // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens.
1735
+ offsets.setDesiredOffset(
1736
+ firstNonObjectToken,
1737
+ offsetBase,
1738
+ 0,
1739
+ );
1740
+ offsets.setDesiredOffset(
1741
+ secondNonObjectToken,
1742
+ firstNonObjectToken,
1743
+ 0,
1744
+ );
1745
+ }
1746
+ },
1747
+
1748
+ NewExpression(node) {
1749
+ // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo`
1750
+ if (
1751
+ node.arguments.length > 0 ||
1752
+ (astUtils.isClosingParenToken(
1753
+ sourceCode.getLastToken(node),
1754
+ ) &&
1755
+ astUtils.isOpeningParenToken(
1756
+ sourceCode.getLastToken(node, 1),
1757
+ ))
1758
+ ) {
1759
+ addFunctionCallIndent(node);
1760
+ }
1761
+ },
1762
+
1763
+ Property(node) {
1764
+ if (!node.shorthand && !node.method && node.kind === "init") {
1765
+ const colon = sourceCode.getFirstTokenBetween(
1766
+ node.key,
1767
+ node.value,
1768
+ astUtils.isColonToken,
1769
+ );
1770
+
1771
+ offsets.ignoreToken(sourceCode.getTokenAfter(colon));
1772
+ }
1773
+ },
1774
+
1775
+ PropertyDefinition(node) {
1776
+ const firstToken = sourceCode.getFirstToken(node);
1777
+ const maybeSemicolonToken = sourceCode.getLastToken(node);
1778
+ let keyLastToken;
1779
+
1780
+ // Indent key.
1781
+ if (node.computed) {
1782
+ const bracketTokenL = sourceCode.getTokenBefore(
1783
+ node.key,
1784
+ astUtils.isOpeningBracketToken,
1785
+ );
1786
+ const bracketTokenR = (keyLastToken =
1787
+ sourceCode.getTokenAfter(
1788
+ node.key,
1789
+ astUtils.isClosingBracketToken,
1790
+ ));
1791
+ const keyRange = [
1792
+ bracketTokenL.range[1],
1793
+ bracketTokenR.range[0],
1794
+ ];
1795
+
1796
+ if (bracketTokenL !== firstToken) {
1797
+ offsets.setDesiredOffset(bracketTokenL, firstToken, 0);
1798
+ }
1799
+ offsets.setDesiredOffsets(keyRange, bracketTokenL, 1);
1800
+ offsets.setDesiredOffset(bracketTokenR, bracketTokenL, 0);
1801
+ } else {
1802
+ const idToken = (keyLastToken = sourceCode.getFirstToken(
1803
+ node.key,
1804
+ ));
1805
+
1806
+ if (idToken !== firstToken) {
1807
+ offsets.setDesiredOffset(idToken, firstToken, 1);
1808
+ }
1809
+ }
1810
+
1811
+ // Indent initializer.
1812
+ if (node.value) {
1813
+ const eqToken = sourceCode.getTokenBefore(
1814
+ node.value,
1815
+ astUtils.isEqToken,
1816
+ );
1817
+ const valueToken = sourceCode.getTokenAfter(eqToken);
1818
+
1819
+ offsets.setDesiredOffset(eqToken, keyLastToken, 1);
1820
+ offsets.setDesiredOffset(valueToken, eqToken, 1);
1821
+ if (astUtils.isSemicolonToken(maybeSemicolonToken)) {
1822
+ offsets.setDesiredOffset(
1823
+ maybeSemicolonToken,
1824
+ eqToken,
1825
+ 1,
1826
+ );
1827
+ }
1828
+ } else if (astUtils.isSemicolonToken(maybeSemicolonToken)) {
1829
+ offsets.setDesiredOffset(
1830
+ maybeSemicolonToken,
1831
+ keyLastToken,
1832
+ 1,
1833
+ );
1834
+ }
1835
+ },
1836
+
1837
+ StaticBlock(node) {
1838
+ const openingCurly = sourceCode.getFirstToken(node, {
1839
+ skip: 1,
1840
+ }); // skip the `static` token
1841
+ const closingCurly = sourceCode.getLastToken(node);
1842
+
1843
+ addElementListIndent(
1844
+ node.body,
1845
+ openingCurly,
1846
+ closingCurly,
1847
+ options.StaticBlock.body,
1848
+ );
1849
+ },
1850
+
1851
+ SwitchStatement(node) {
1852
+ const openingCurly = sourceCode.getTokenAfter(
1853
+ node.discriminant,
1854
+ astUtils.isOpeningBraceToken,
1855
+ );
1856
+ const closingCurly = sourceCode.getLastToken(node);
1857
+
1858
+ offsets.setDesiredOffsets(
1859
+ [openingCurly.range[1], closingCurly.range[0]],
1860
+ openingCurly,
1861
+ options.SwitchCase,
1862
+ );
1863
+
1864
+ if (node.cases.length) {
1865
+ sourceCode
1866
+ .getTokensBetween(node.cases.at(-1), closingCurly, {
1867
+ includeComments: true,
1868
+ filter: astUtils.isCommentToken,
1869
+ })
1870
+ .forEach(token => offsets.ignoreToken(token));
1871
+ }
1872
+ },
1873
+
1874
+ SwitchCase(node) {
1875
+ if (
1876
+ !(
1877
+ node.consequent.length === 1 &&
1878
+ node.consequent[0].type === "BlockStatement"
1879
+ )
1880
+ ) {
1881
+ const caseKeyword = sourceCode.getFirstToken(node);
1882
+ const tokenAfterCurrentCase =
1883
+ sourceCode.getTokenAfter(node);
1884
+
1885
+ offsets.setDesiredOffsets(
1886
+ [caseKeyword.range[1], tokenAfterCurrentCase.range[0]],
1887
+ caseKeyword,
1888
+ 1,
1889
+ );
1890
+ }
1891
+ },
1892
+
1893
+ TemplateLiteral(node) {
1894
+ node.expressions.forEach((expression, index) => {
1895
+ const previousQuasi = node.quasis[index];
1896
+ const nextQuasi = node.quasis[index + 1];
1897
+ const tokenToAlignFrom =
1898
+ previousQuasi.loc.start.line ===
1899
+ previousQuasi.loc.end.line
1900
+ ? sourceCode.getFirstToken(previousQuasi)
1901
+ : null;
1902
+
1903
+ offsets.setDesiredOffsets(
1904
+ [previousQuasi.range[1], nextQuasi.range[0]],
1905
+ tokenToAlignFrom,
1906
+ 1,
1907
+ );
1908
+ offsets.setDesiredOffset(
1909
+ sourceCode.getFirstToken(nextQuasi),
1910
+ tokenToAlignFrom,
1911
+ 0,
1912
+ );
1913
+ });
1914
+ },
1915
+
1916
+ VariableDeclaration(node) {
1917
+ let variableIndent = Object.hasOwn(
1918
+ options.VariableDeclarator,
1919
+ node.kind,
1920
+ )
1921
+ ? options.VariableDeclarator[node.kind]
1922
+ : DEFAULT_VARIABLE_INDENT;
1923
+
1924
+ const firstToken = sourceCode.getFirstToken(node),
1925
+ lastToken = sourceCode.getLastToken(node);
1926
+
1927
+ if (options.VariableDeclarator[node.kind] === "first") {
1928
+ if (node.declarations.length > 1) {
1929
+ addElementListIndent(
1930
+ node.declarations,
1931
+ firstToken,
1932
+ lastToken,
1933
+ "first",
1934
+ );
1935
+ return;
1936
+ }
1937
+
1938
+ variableIndent = DEFAULT_VARIABLE_INDENT;
1939
+ }
1940
+
1941
+ if (
1942
+ node.declarations.at(-1).loc.start.line >
1943
+ node.loc.start.line
1944
+ ) {
1945
+ /*
1946
+ * VariableDeclarator indentation is a bit different from other forms of indentation, in that the
1947
+ * indentation of an opening bracket sometimes won't match that of a closing bracket. For example,
1948
+ * the following indentations are correct:
1949
+ *
1950
+ * var foo = {
1951
+ * ok: true
1952
+ * };
1953
+ *
1954
+ * var foo = {
1955
+ * ok: true,
1956
+ * },
1957
+ * bar = 1;
1958
+ *
1959
+ * Account for when exiting the AST (after indentations have already been set for the nodes in
1960
+ * the declaration) by manually increasing the indentation level of the tokens in this declarator
1961
+ * on the same line as the start of the declaration, provided that there are declarators that
1962
+ * follow this one.
1963
+ */
1964
+ offsets.setDesiredOffsets(
1965
+ node.range,
1966
+ firstToken,
1967
+ variableIndent,
1968
+ true,
1969
+ );
1970
+ } else {
1971
+ offsets.setDesiredOffsets(
1972
+ node.range,
1973
+ firstToken,
1974
+ variableIndent,
1975
+ );
1976
+ }
1977
+
1978
+ if (astUtils.isSemicolonToken(lastToken)) {
1979
+ offsets.ignoreToken(lastToken);
1980
+ }
1981
+ },
1982
+
1983
+ VariableDeclarator(node) {
1984
+ if (node.init) {
1985
+ const equalOperator = sourceCode.getTokenBefore(
1986
+ node.init,
1987
+ astUtils.isNotOpeningParenToken,
1988
+ );
1989
+ const tokenAfterOperator =
1990
+ sourceCode.getTokenAfter(equalOperator);
1991
+
1992
+ offsets.ignoreToken(equalOperator);
1993
+ offsets.ignoreToken(tokenAfterOperator);
1994
+ offsets.setDesiredOffsets(
1995
+ [tokenAfterOperator.range[0], node.range[1]],
1996
+ equalOperator,
1997
+ 1,
1998
+ );
1999
+ offsets.setDesiredOffset(
2000
+ equalOperator,
2001
+ sourceCode.getLastToken(node.id),
2002
+ 0,
2003
+ );
2004
+ }
2005
+ },
2006
+
2007
+ "JSXAttribute[value]"(node) {
2008
+ const equalsToken = sourceCode.getFirstTokenBetween(
2009
+ node.name,
2010
+ node.value,
2011
+ token => token.type === "Punctuator" && token.value === "=",
2012
+ );
2013
+
2014
+ offsets.setDesiredOffsets(
2015
+ [equalsToken.range[0], node.value.range[1]],
2016
+ sourceCode.getFirstToken(node.name),
2017
+ 1,
2018
+ );
2019
+ },
2020
+
2021
+ JSXElement(node) {
2022
+ if (node.closingElement) {
2023
+ addElementListIndent(
2024
+ node.children,
2025
+ sourceCode.getFirstToken(node.openingElement),
2026
+ sourceCode.getFirstToken(node.closingElement),
2027
+ 1,
2028
+ );
2029
+ }
2030
+ },
2031
+
2032
+ JSXOpeningElement(node) {
2033
+ const firstToken = sourceCode.getFirstToken(node);
2034
+ let closingToken;
2035
+
2036
+ if (node.selfClosing) {
2037
+ closingToken = sourceCode.getLastToken(node, { skip: 1 });
2038
+ offsets.setDesiredOffset(
2039
+ sourceCode.getLastToken(node),
2040
+ closingToken,
2041
+ 0,
2042
+ );
2043
+ } else {
2044
+ closingToken = sourceCode.getLastToken(node);
2045
+ }
2046
+ offsets.setDesiredOffsets(
2047
+ node.name.range,
2048
+ sourceCode.getFirstToken(node),
2049
+ );
2050
+ addElementListIndent(
2051
+ node.attributes,
2052
+ firstToken,
2053
+ closingToken,
2054
+ 1,
2055
+ );
2056
+ },
2057
+
2058
+ JSXClosingElement(node) {
2059
+ const firstToken = sourceCode.getFirstToken(node);
2060
+
2061
+ offsets.setDesiredOffsets(node.name.range, firstToken, 1);
2062
+ },
2063
+
2064
+ JSXFragment(node) {
2065
+ const firstOpeningToken = sourceCode.getFirstToken(
2066
+ node.openingFragment,
2067
+ );
2068
+ const firstClosingToken = sourceCode.getFirstToken(
2069
+ node.closingFragment,
2070
+ );
2071
+
2072
+ addElementListIndent(
2073
+ node.children,
2074
+ firstOpeningToken,
2075
+ firstClosingToken,
2076
+ 1,
2077
+ );
2078
+ },
2079
+
2080
+ JSXOpeningFragment(node) {
2081
+ const firstToken = sourceCode.getFirstToken(node);
2082
+ const closingToken = sourceCode.getLastToken(node);
2083
+
2084
+ offsets.setDesiredOffsets(node.range, firstToken, 1);
2085
+ offsets.matchOffsetOf(firstToken, closingToken);
2086
+ },
2087
+
2088
+ JSXClosingFragment(node) {
2089
+ const firstToken = sourceCode.getFirstToken(node);
2090
+ const slashToken = sourceCode.getLastToken(node, { skip: 1 });
2091
+ const closingToken = sourceCode.getLastToken(node);
2092
+ const tokenToMatch = astUtils.isTokenOnSameLine(
2093
+ slashToken,
2094
+ closingToken,
2095
+ )
2096
+ ? slashToken
2097
+ : closingToken;
2098
+
2099
+ offsets.setDesiredOffsets(node.range, firstToken, 1);
2100
+ offsets.matchOffsetOf(firstToken, tokenToMatch);
2101
+ },
2102
+
2103
+ JSXExpressionContainer(node) {
2104
+ const openingCurly = sourceCode.getFirstToken(node);
2105
+ const closingCurly = sourceCode.getLastToken(node);
2106
+
2107
+ offsets.setDesiredOffsets(
2108
+ [openingCurly.range[1], closingCurly.range[0]],
2109
+ openingCurly,
2110
+ 1,
2111
+ );
2112
+ },
2113
+
2114
+ JSXSpreadAttribute(node) {
2115
+ const openingCurly = sourceCode.getFirstToken(node);
2116
+ const closingCurly = sourceCode.getLastToken(node);
2117
+
2118
+ offsets.setDesiredOffsets(
2119
+ [openingCurly.range[1], closingCurly.range[0]],
2120
+ openingCurly,
2121
+ 1,
2122
+ );
2123
+ },
2124
+
2125
+ "*"(node) {
2126
+ const firstToken = sourceCode.getFirstToken(node);
2127
+
2128
+ // Ensure that the children of every node are indented at least as much as the first token.
2129
+ if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) {
2130
+ offsets.setDesiredOffsets(node.range, firstToken, 0);
2131
+ }
2132
+ },
2133
+ };
2134
+
2135
+ const listenerCallQueue = [];
2136
+
2137
+ /*
2138
+ * To ignore the indentation of a node:
2139
+ * 1. Don't call the node's listener when entering it (if it has a listener)
2140
+ * 2. Don't set any offsets against the first token of the node.
2141
+ * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets.
2142
+ */
2143
+ const offsetListeners = {};
2144
+
2145
+ for (const [selector, listener] of Object.entries(
2146
+ baseOffsetListeners,
2147
+ )) {
2148
+ /*
2149
+ * Offset listener calls are deferred until traversal is finished, and are called as
2150
+ * part of the final `Program:exit` listener. This is necessary because a node might
2151
+ * be matched by multiple selectors.
2152
+ *
2153
+ * Example: Suppose there is an offset listener for `Identifier`, and the user has
2154
+ * specified in configuration that `MemberExpression > Identifier` should be ignored.
2155
+ * Due to selector specificity rules, the `Identifier` listener will get called first. However,
2156
+ * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener
2157
+ * should not have been called at all. Without doing extra selector matching, we don't know
2158
+ * whether the Identifier matches the `MemberExpression > Identifier` selector until the
2159
+ * `MemberExpression > Identifier` listener is called.
2160
+ *
2161
+ * To avoid this, the `Identifier` listener isn't called until traversal finishes and all
2162
+ * ignored nodes are known.
2163
+ */
2164
+ offsetListeners[selector] = node =>
2165
+ listenerCallQueue.push({ listener, node });
2166
+ }
2167
+
2168
+ // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set.
2169
+ const ignoredNodes = new Set();
2170
+
2171
+ /**
2172
+ * Ignores a node
2173
+ * @param {ASTNode} node The node to ignore
2174
+ * @returns {void}
2175
+ */
2176
+ function addToIgnoredNodes(node) {
2177
+ ignoredNodes.add(node);
2178
+ ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node));
2179
+ }
2180
+
2181
+ const ignoredNodeListeners = options.ignoredNodes.reduce(
2182
+ (listeners, ignoredSelector) =>
2183
+ Object.assign(listeners, {
2184
+ [ignoredSelector]: addToIgnoredNodes,
2185
+ }),
2186
+ {},
2187
+ );
2188
+
2189
+ /*
2190
+ * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation
2191
+ * at the end.
2192
+ *
2193
+ * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears
2194
+ * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored,
2195
+ * so those listeners wouldn't be called anyway.
2196
+ */
2197
+ return Object.assign(offsetListeners, ignoredNodeListeners, {
2198
+ "*:exit"(node) {
2199
+ // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it.
2200
+ if (!KNOWN_NODES.has(node.type)) {
2201
+ addToIgnoredNodes(node);
2202
+ }
2203
+ },
2204
+ "Program:exit"() {
2205
+ // If ignoreComments option is enabled, ignore all comment tokens.
2206
+ if (options.ignoreComments) {
2207
+ sourceCode
2208
+ .getAllComments()
2209
+ .forEach(comment => offsets.ignoreToken(comment));
2210
+ }
2211
+
2212
+ // Invoke the queued offset listeners for the nodes that aren't ignored.
2213
+ for (let i = 0; i < listenerCallQueue.length; i++) {
2214
+ const nodeInfo = listenerCallQueue[i];
2215
+
2216
+ if (!ignoredNodes.has(nodeInfo.node)) {
2217
+ nodeInfo.listener(nodeInfo.node);
2218
+ }
2219
+ }
2220
+
2221
+ // Update the offsets for ignored nodes to prevent their child tokens from being reported.
2222
+ ignoredNodes.forEach(ignoreNode);
2223
+
2224
+ addParensIndent(sourceCode.ast.tokens);
2225
+
2226
+ /*
2227
+ * Create a Map from (tokenOrComment) => (precedingToken).
2228
+ * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly.
2229
+ */
2230
+ const precedingTokens = new WeakMap();
2231
+
2232
+ for (let i = 0; i < sourceCode.ast.comments.length; i++) {
2233
+ const comment = sourceCode.ast.comments[i];
2234
+
2235
+ const tokenOrCommentBefore = sourceCode.getTokenBefore(
2236
+ comment,
2237
+ { includeComments: true },
2238
+ );
2239
+ const hasToken = precedingTokens.has(tokenOrCommentBefore)
2240
+ ? precedingTokens.get(tokenOrCommentBefore)
2241
+ : tokenOrCommentBefore;
2242
+
2243
+ precedingTokens.set(comment, hasToken);
2244
+ }
2245
+
2246
+ for (let i = 1; i < sourceCode.lines.length + 1; i++) {
2247
+ if (!tokenInfo.firstTokensByLineNumber.has(i)) {
2248
+ // Don't check indentation on blank lines
2249
+ continue;
2250
+ }
2251
+
2252
+ const firstTokenOfLine =
2253
+ tokenInfo.firstTokensByLineNumber.get(i);
2254
+
2255
+ if (firstTokenOfLine.loc.start.line !== i) {
2256
+ // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice.
2257
+ continue;
2258
+ }
2259
+
2260
+ if (astUtils.isCommentToken(firstTokenOfLine)) {
2261
+ const tokenBefore =
2262
+ precedingTokens.get(firstTokenOfLine);
2263
+ const tokenAfter = tokenBefore
2264
+ ? sourceCode.getTokenAfter(tokenBefore)
2265
+ : sourceCode.ast.tokens[0];
2266
+ const mayAlignWithBefore =
2267
+ tokenBefore &&
2268
+ !hasBlankLinesBetween(
2269
+ tokenBefore,
2270
+ firstTokenOfLine,
2271
+ );
2272
+ const mayAlignWithAfter =
2273
+ tokenAfter &&
2274
+ !hasBlankLinesBetween(firstTokenOfLine, tokenAfter);
2275
+
2276
+ /*
2277
+ * If a comment precedes a line that begins with a semicolon token, align to that token, i.e.
2278
+ *
2279
+ * let foo
2280
+ * // comment
2281
+ * ;(async () => {})()
2282
+ */
2283
+ if (
2284
+ tokenAfter &&
2285
+ astUtils.isSemicolonToken(tokenAfter) &&
2286
+ !astUtils.isTokenOnSameLine(
2287
+ firstTokenOfLine,
2288
+ tokenAfter,
2289
+ )
2290
+ ) {
2291
+ offsets.setDesiredOffset(
2292
+ firstTokenOfLine,
2293
+ tokenAfter,
2294
+ 0,
2295
+ );
2296
+ }
2297
+
2298
+ // If a comment matches the expected indentation of the token immediately before or after, don't report it.
2299
+ if (
2300
+ (mayAlignWithBefore &&
2301
+ validateTokenIndent(
2302
+ firstTokenOfLine,
2303
+ offsets.getDesiredIndent(tokenBefore),
2304
+ )) ||
2305
+ (mayAlignWithAfter &&
2306
+ validateTokenIndent(
2307
+ firstTokenOfLine,
2308
+ offsets.getDesiredIndent(tokenAfter),
2309
+ ))
2310
+ ) {
2311
+ continue;
2312
+ }
2313
+ }
2314
+
2315
+ // If the token matches the expected indentation, don't report it.
2316
+ if (
2317
+ validateTokenIndent(
2318
+ firstTokenOfLine,
2319
+ offsets.getDesiredIndent(firstTokenOfLine),
2320
+ )
2321
+ ) {
2322
+ continue;
2323
+ }
2324
+
2325
+ // Otherwise, report the token/comment.
2326
+ report(
2327
+ firstTokenOfLine,
2328
+ offsets.getDesiredIndent(firstTokenOfLine),
2329
+ );
2330
+ }
2331
+ },
2332
+ });
2333
+ },
1821
2334
  };