eslint 8.57.1 → 9.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (458) hide show
  1. package/README.md +165 -115
  2. package/bin/eslint.js +112 -89
  3. package/conf/default-cli-options.js +22 -22
  4. package/conf/ecma-version.js +16 -0
  5. package/conf/globals.js +109 -94
  6. package/conf/replacements.json +24 -20
  7. package/conf/rule-type-list.json +89 -26
  8. package/lib/api.js +16 -20
  9. package/lib/cli-engine/cli-engine.js +841 -810
  10. package/lib/cli-engine/file-enumerator.js +384 -390
  11. package/lib/cli-engine/formatters/formatters-meta.json +17 -45
  12. package/lib/cli-engine/formatters/html.js +110 -102
  13. package/lib/cli-engine/formatters/json-with-metadata.js +5 -5
  14. package/lib/cli-engine/formatters/json.js +2 -2
  15. package/lib/cli-engine/formatters/stylish.js +97 -76
  16. package/lib/cli-engine/hash.js +1 -1
  17. package/lib/cli-engine/index.js +1 -1
  18. package/lib/cli-engine/lint-result-cache.js +165 -148
  19. package/lib/cli-engine/load-rules.js +17 -17
  20. package/lib/cli.js +481 -399
  21. package/lib/config/config-loader.js +816 -0
  22. package/lib/config/config.js +674 -0
  23. package/lib/config/default-config.js +57 -46
  24. package/lib/config/flat-config-array.js +170 -333
  25. package/lib/config/flat-config-schema.js +389 -389
  26. package/lib/config-api.js +12 -0
  27. package/lib/eslint/eslint-helpers.js +1196 -663
  28. package/lib/eslint/eslint.js +1262 -607
  29. package/lib/eslint/index.js +3 -3
  30. package/lib/eslint/legacy-eslint.js +786 -0
  31. package/lib/eslint/worker.js +173 -0
  32. package/lib/languages/js/index.js +336 -0
  33. package/lib/languages/js/source-code/index.js +7 -0
  34. package/lib/languages/js/source-code/source-code.js +1364 -0
  35. package/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js +61 -0
  36. package/lib/languages/js/source-code/token-store/backward-token-cursor.js +57 -0
  37. package/lib/{source-code → languages/js/source-code}/token-store/cursor.js +36 -36
  38. package/lib/languages/js/source-code/token-store/cursors.js +120 -0
  39. package/lib/{source-code → languages/js/source-code}/token-store/decorative-cursor.js +17 -18
  40. package/lib/{source-code → languages/js/source-code}/token-store/filter-cursor.js +19 -20
  41. package/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js +65 -0
  42. package/lib/languages/js/source-code/token-store/forward-token-cursor.js +62 -0
  43. package/lib/languages/js/source-code/token-store/index.js +721 -0
  44. package/lib/{source-code → languages/js/source-code}/token-store/limit-cursor.js +17 -18
  45. package/lib/languages/js/source-code/token-store/padded-token-cursor.js +45 -0
  46. package/lib/{source-code → languages/js/source-code}/token-store/skip-cursor.js +19 -20
  47. package/lib/languages/js/source-code/token-store/utils.js +110 -0
  48. package/lib/languages/js/validate-language-options.js +196 -0
  49. package/lib/linter/apply-disable-directives.js +490 -371
  50. package/lib/linter/code-path-analysis/code-path-analyzer.js +650 -674
  51. package/lib/linter/code-path-analysis/code-path-segment.js +215 -216
  52. package/lib/linter/code-path-analysis/code-path-state.js +2118 -2096
  53. package/lib/linter/code-path-analysis/code-path.js +307 -317
  54. package/lib/linter/code-path-analysis/debug-helpers.js +183 -163
  55. package/lib/linter/code-path-analysis/fork-context.js +297 -272
  56. package/lib/linter/code-path-analysis/id-generator.js +22 -23
  57. package/lib/linter/esquery.js +332 -0
  58. package/lib/linter/file-context.js +144 -0
  59. package/lib/linter/file-report.js +608 -0
  60. package/lib/linter/index.js +3 -5
  61. package/lib/linter/interpolate.js +38 -16
  62. package/lib/linter/linter.js +2328 -1785
  63. package/lib/linter/rule-fixer.js +136 -107
  64. package/lib/linter/rules.js +37 -46
  65. package/lib/linter/source-code-fixer.js +96 -94
  66. package/lib/linter/source-code-traverser.js +333 -0
  67. package/lib/linter/source-code-visitor.js +81 -0
  68. package/lib/linter/timing.js +145 -97
  69. package/lib/linter/vfile.js +115 -0
  70. package/lib/options.js +464 -326
  71. package/lib/rule-tester/index.js +3 -1
  72. package/lib/rule-tester/rule-tester.js +1371 -998
  73. package/lib/rules/accessor-pairs.js +333 -259
  74. package/lib/rules/array-bracket-newline.js +250 -220
  75. package/lib/rules/array-bracket-spacing.js +286 -229
  76. package/lib/rules/array-callback-return.js +401 -354
  77. package/lib/rules/array-element-newline.js +358 -295
  78. package/lib/rules/arrow-body-style.js +400 -278
  79. package/lib/rules/arrow-parens.js +206 -155
  80. package/lib/rules/arrow-spacing.js +169 -145
  81. package/lib/rules/block-scoped-var.js +125 -123
  82. package/lib/rules/block-spacing.js +186 -158
  83. package/lib/rules/brace-style.js +262 -181
  84. package/lib/rules/callback-return.js +203 -174
  85. package/lib/rules/camelcase.js +403 -380
  86. package/lib/rules/capitalized-comments.js +253 -228
  87. package/lib/rules/class-methods-use-this.js +231 -168
  88. package/lib/rules/comma-dangle.js +379 -328
  89. package/lib/rules/comma-spacing.js +193 -177
  90. package/lib/rules/comma-style.js +375 -298
  91. package/lib/rules/complexity.js +180 -144
  92. package/lib/rules/computed-property-spacing.js +236 -193
  93. package/lib/rules/consistent-return.js +181 -170
  94. package/lib/rules/consistent-this.js +167 -141
  95. package/lib/rules/constructor-super.js +418 -411
  96. package/lib/rules/curly.js +407 -468
  97. package/lib/rules/default-case-last.js +39 -32
  98. package/lib/rules/default-case.js +89 -83
  99. package/lib/rules/default-param-last.js +69 -53
  100. package/lib/rules/dot-location.js +122 -92
  101. package/lib/rules/dot-notation.js +193 -153
  102. package/lib/rules/eol-last.js +122 -102
  103. package/lib/rules/eqeqeq.js +191 -155
  104. package/lib/rules/for-direction.js +150 -122
  105. package/lib/rules/func-call-spacing.js +261 -213
  106. package/lib/rules/func-name-matching.js +294 -209
  107. package/lib/rules/func-names.js +165 -164
  108. package/lib/rules/func-style.js +209 -86
  109. package/lib/rules/function-call-argument-newline.js +152 -111
  110. package/lib/rules/function-paren-newline.js +349 -273
  111. package/lib/rules/generator-star-spacing.js +229 -192
  112. package/lib/rules/getter-return.js +208 -170
  113. package/lib/rules/global-require.js +85 -58
  114. package/lib/rules/grouped-accessor-pairs.js +201 -148
  115. package/lib/rules/guard-for-in.js +72 -63
  116. package/lib/rules/handle-callback-err.js +108 -87
  117. package/lib/rules/id-blacklist.js +182 -187
  118. package/lib/rules/id-denylist.js +174 -179
  119. package/lib/rules/id-length.js +197 -157
  120. package/lib/rules/id-match.js +350 -286
  121. package/lib/rules/implicit-arrow-linebreak.js +102 -61
  122. package/lib/rules/indent-legacy.js +1345 -1102
  123. package/lib/rules/indent.js +2272 -1741
  124. package/lib/rules/index.js +320 -294
  125. package/lib/rules/init-declarations.js +139 -106
  126. package/lib/rules/jsx-quotes.js +94 -64
  127. package/lib/rules/key-spacing.js +750 -615
  128. package/lib/rules/keyword-spacing.js +648 -587
  129. package/lib/rules/line-comment-position.js +143 -108
  130. package/lib/rules/linebreak-style.js +115 -88
  131. package/lib/rules/lines-around-comment.js +540 -430
  132. package/lib/rules/lines-around-directive.js +233 -185
  133. package/lib/rules/lines-between-class-members.js +305 -216
  134. package/lib/rules/logical-assignment-operators.js +582 -398
  135. package/lib/rules/max-classes-per-file.js +69 -68
  136. package/lib/rules/max-depth.js +146 -143
  137. package/lib/rules/max-len.js +473 -416
  138. package/lib/rules/max-lines-per-function.js +201 -176
  139. package/lib/rules/max-lines.js +158 -162
  140. package/lib/rules/max-nested-callbacks.js +102 -104
  141. package/lib/rules/max-params.js +102 -75
  142. package/lib/rules/max-statements-per-line.js +205 -180
  143. package/lib/rules/max-statements.js +168 -164
  144. package/lib/rules/multiline-comment-style.js +638 -460
  145. package/lib/rules/multiline-ternary.js +241 -158
  146. package/lib/rules/new-cap.js +233 -232
  147. package/lib/rules/new-parens.js +88 -61
  148. package/lib/rules/newline-after-var.js +287 -233
  149. package/lib/rules/newline-before-return.js +229 -204
  150. package/lib/rules/newline-per-chained-call.js +142 -109
  151. package/lib/rules/no-alert.js +90 -79
  152. package/lib/rules/no-array-constructor.js +175 -113
  153. package/lib/rules/no-async-promise-executor.js +30 -24
  154. package/lib/rules/no-await-in-loop.js +79 -70
  155. package/lib/rules/no-bitwise.js +113 -87
  156. package/lib/rules/no-buffer-constructor.js +61 -37
  157. package/lib/rules/no-caller.js +39 -33
  158. package/lib/rules/no-case-declarations.js +61 -45
  159. package/lib/rules/no-catch-shadow.js +76 -62
  160. package/lib/rules/no-class-assign.js +51 -48
  161. package/lib/rules/no-compare-neg-zero.js +62 -48
  162. package/lib/rules/no-cond-assign.js +148 -132
  163. package/lib/rules/no-confusing-arrow.js +98 -63
  164. package/lib/rules/no-console.js +202 -188
  165. package/lib/rules/no-const-assign.js +58 -41
  166. package/lib/rules/no-constant-binary-expression.js +501 -407
  167. package/lib/rules/no-constant-condition.js +158 -131
  168. package/lib/rules/no-constructor-return.js +49 -49
  169. package/lib/rules/no-continue.js +25 -26
  170. package/lib/rules/no-control-regex.js +125 -121
  171. package/lib/rules/no-debugger.js +28 -30
  172. package/lib/rules/no-delete-var.js +29 -29
  173. package/lib/rules/no-div-regex.js +47 -40
  174. package/lib/rules/no-dupe-args.js +79 -69
  175. package/lib/rules/no-dupe-class-members.js +102 -89
  176. package/lib/rules/no-dupe-else-if.js +100 -77
  177. package/lib/rules/no-dupe-keys.js +133 -110
  178. package/lib/rules/no-duplicate-case.js +50 -43
  179. package/lib/rules/no-duplicate-imports.js +266 -188
  180. package/lib/rules/no-else-return.js +430 -385
  181. package/lib/rules/no-empty-character-class.js +57 -50
  182. package/lib/rules/no-empty-function.js +197 -128
  183. package/lib/rules/no-empty-pattern.js +63 -56
  184. package/lib/rules/no-empty-static-block.js +61 -35
  185. package/lib/rules/no-empty.js +135 -85
  186. package/lib/rules/no-eq-null.js +37 -32
  187. package/lib/rules/no-eval.js +258 -249
  188. package/lib/rules/no-ex-assign.js +42 -39
  189. package/lib/rules/no-extend-native.js +161 -160
  190. package/lib/rules/no-extra-bind.js +201 -190
  191. package/lib/rules/no-extra-boolean-cast.js +398 -295
  192. package/lib/rules/no-extra-label.js +150 -130
  193. package/lib/rules/no-extra-parens.js +1654 -1307
  194. package/lib/rules/no-extra-semi.js +146 -126
  195. package/lib/rules/no-fallthrough.js +200 -136
  196. package/lib/rules/no-floating-decimal.js +74 -48
  197. package/lib/rules/no-func-assign.js +54 -55
  198. package/lib/rules/no-global-assign.js +78 -72
  199. package/lib/rules/no-implicit-coercion.js +350 -262
  200. package/lib/rules/no-implicit-globals.js +174 -133
  201. package/lib/rules/no-implied-eval.js +150 -112
  202. package/lib/rules/no-import-assign.js +145 -159
  203. package/lib/rules/no-inline-comments.js +101 -96
  204. package/lib/rules/no-inner-declarations.js +115 -78
  205. package/lib/rules/no-invalid-regexp.js +223 -174
  206. package/lib/rules/no-invalid-this.js +145 -117
  207. package/lib/rules/no-irregular-whitespace.js +266 -250
  208. package/lib/rules/no-iterator.js +29 -33
  209. package/lib/rules/no-label-var.js +59 -61
  210. package/lib/rules/no-labels.js +138 -131
  211. package/lib/rules/no-lone-blocks.js +127 -123
  212. package/lib/rules/no-lonely-if.js +105 -67
  213. package/lib/rules/no-loop-func.js +245 -184
  214. package/lib/rules/no-loss-of-precision.js +236 -201
  215. package/lib/rules/no-magic-numbers.js +339 -217
  216. package/lib/rules/no-misleading-character-class.js +548 -253
  217. package/lib/rules/no-mixed-operators.js +188 -164
  218. package/lib/rules/no-mixed-requires.js +253 -224
  219. package/lib/rules/no-mixed-spaces-and-tabs.js +135 -103
  220. package/lib/rules/no-multi-assign.js +46 -47
  221. package/lib/rules/no-multi-spaces.js +163 -125
  222. package/lib/rules/no-multi-str.js +42 -40
  223. package/lib/rules/no-multiple-empty-lines.js +196 -140
  224. package/lib/rules/no-native-reassign.js +90 -74
  225. package/lib/rules/no-negated-condition.js +79 -74
  226. package/lib/rules/no-negated-in-lhs.js +45 -32
  227. package/lib/rules/no-nested-ternary.js +33 -31
  228. package/lib/rules/no-new-func.js +71 -62
  229. package/lib/rules/no-new-native-nonconstructor.js +43 -39
  230. package/lib/rules/no-new-object.js +48 -39
  231. package/lib/rules/no-new-require.js +48 -31
  232. package/lib/rules/no-new-symbol.js +61 -43
  233. package/lib/rules/no-new-wrappers.js +43 -41
  234. package/lib/rules/no-new.js +28 -29
  235. package/lib/rules/no-nonoctal-decimal-escape.js +149 -121
  236. package/lib/rules/no-obj-calls.js +66 -53
  237. package/lib/rules/no-object-constructor.js +104 -97
  238. package/lib/rules/no-octal-escape.js +40 -43
  239. package/lib/rules/no-octal.js +29 -32
  240. package/lib/rules/no-param-reassign.js +236 -218
  241. package/lib/rules/no-path-concat.js +66 -51
  242. package/lib/rules/no-plusplus.js +60 -63
  243. package/lib/rules/no-process-env.js +49 -32
  244. package/lib/rules/no-process-exit.js +48 -28
  245. package/lib/rules/no-promise-executor-return.js +205 -204
  246. package/lib/rules/no-proto.js +26 -29
  247. package/lib/rules/no-prototype-builtins.js +146 -124
  248. package/lib/rules/no-redeclare.js +154 -155
  249. package/lib/rules/no-regex-spaces.js +183 -161
  250. package/lib/rules/no-restricted-exports.js +208 -174
  251. package/lib/rules/no-restricted-globals.js +254 -112
  252. package/lib/rules/no-restricted-imports.js +824 -384
  253. package/lib/rules/no-restricted-modules.js +222 -186
  254. package/lib/rules/no-restricted-properties.js +218 -153
  255. package/lib/rules/no-restricted-syntax.js +56 -52
  256. package/lib/rules/no-return-assign.js +56 -49
  257. package/lib/rules/no-return-await.js +147 -120
  258. package/lib/rules/no-script-url.js +53 -46
  259. package/lib/rules/no-self-assign.js +148 -145
  260. package/lib/rules/no-self-compare.js +63 -46
  261. package/lib/rules/no-sequences.js +135 -115
  262. package/lib/rules/no-setter-return.js +176 -178
  263. package/lib/rules/no-shadow-restricted-names.js +84 -36
  264. package/lib/rules/no-shadow.js +598 -310
  265. package/lib/rules/no-spaced-func.js +82 -60
  266. package/lib/rules/no-sparse-arrays.js +46 -28
  267. package/lib/rules/no-sync.js +61 -44
  268. package/lib/rules/no-tabs.js +83 -54
  269. package/lib/rules/no-template-curly-in-string.js +33 -32
  270. package/lib/rules/no-ternary.js +25 -28
  271. package/lib/rules/no-this-before-super.js +332 -298
  272. package/lib/rules/no-throw-literal.js +31 -36
  273. package/lib/rules/no-trailing-spaces.js +208 -174
  274. package/lib/rules/no-unassigned-vars.js +80 -0
  275. package/lib/rules/no-undef-init.js +86 -60
  276. package/lib/rules/no-undef.js +52 -47
  277. package/lib/rules/no-undefined.js +73 -74
  278. package/lib/rules/no-underscore-dangle.js +370 -322
  279. package/lib/rules/no-unexpected-multiline.js +112 -102
  280. package/lib/rules/no-unmodified-loop-condition.js +254 -254
  281. package/lib/rules/no-unneeded-ternary.js +212 -146
  282. package/lib/rules/no-unreachable-loop.js +145 -140
  283. package/lib/rules/no-unreachable.js +255 -248
  284. package/lib/rules/no-unsafe-finally.js +93 -85
  285. package/lib/rules/no-unsafe-negation.js +105 -81
  286. package/lib/rules/no-unsafe-optional-chaining.js +193 -177
  287. package/lib/rules/no-unused-expressions.js +199 -158
  288. package/lib/rules/no-unused-labels.js +139 -124
  289. package/lib/rules/no-unused-private-class-members.js +206 -182
  290. package/lib/rules/no-unused-vars.js +1708 -687
  291. package/lib/rules/no-use-before-define.js +327 -229
  292. package/lib/rules/no-useless-assignment.js +654 -0
  293. package/lib/rules/no-useless-backreference.js +212 -143
  294. package/lib/rules/no-useless-call.js +58 -53
  295. package/lib/rules/no-useless-catch.js +40 -40
  296. package/lib/rules/no-useless-computed-key.js +144 -108
  297. package/lib/rules/no-useless-concat.js +65 -59
  298. package/lib/rules/no-useless-constructor.js +160 -97
  299. package/lib/rules/no-useless-escape.js +364 -291
  300. package/lib/rules/no-useless-rename.js +183 -153
  301. package/lib/rules/no-useless-return.js +344 -307
  302. package/lib/rules/no-var.js +245 -212
  303. package/lib/rules/no-void.js +51 -46
  304. package/lib/rules/no-warning-comments.js +191 -183
  305. package/lib/rules/no-whitespace-before-property.js +131 -97
  306. package/lib/rules/no-with.js +24 -26
  307. package/lib/rules/nonblock-statement-body-position.js +149 -112
  308. package/lib/rules/object-curly-newline.js +306 -247
  309. package/lib/rules/object-curly-spacing.js +360 -296
  310. package/lib/rules/object-property-newline.js +137 -88
  311. package/lib/rules/object-shorthand.js +632 -500
  312. package/lib/rules/one-var-declaration-per-line.js +104 -82
  313. package/lib/rules/one-var.js +686 -536
  314. package/lib/rules/operator-assignment.js +219 -158
  315. package/lib/rules/operator-linebreak.js +295 -233
  316. package/lib/rules/padded-blocks.js +346 -290
  317. package/lib/rules/padding-line-between-statements.js +443 -421
  318. package/lib/rules/prefer-arrow-callback.js +371 -315
  319. package/lib/rules/prefer-const.js +418 -373
  320. package/lib/rules/prefer-destructuring.js +309 -278
  321. package/lib/rules/prefer-exponentiation-operator.js +176 -132
  322. package/lib/rules/prefer-named-capture-group.js +160 -141
  323. package/lib/rules/prefer-numeric-literals.js +121 -112
  324. package/lib/rules/prefer-object-has-own.js +116 -82
  325. package/lib/rules/prefer-object-spread.js +214 -193
  326. package/lib/rules/prefer-promise-reject-errors.js +140 -118
  327. package/lib/rules/prefer-reflect.js +126 -103
  328. package/lib/rules/prefer-regex-literals.js +561 -463
  329. package/lib/rules/prefer-rest-params.js +79 -80
  330. package/lib/rules/prefer-spread.js +47 -43
  331. package/lib/rules/prefer-template.js +266 -194
  332. package/lib/rules/preserve-caught-error.js +535 -0
  333. package/lib/rules/quote-props.js +373 -289
  334. package/lib/rules/quotes.js +374 -308
  335. package/lib/rules/radix.js +152 -134
  336. package/lib/rules/require-atomic-updates.js +316 -282
  337. package/lib/rules/require-await.js +153 -82
  338. package/lib/rules/require-unicode-regexp.js +296 -108
  339. package/lib/rules/require-yield.js +53 -54
  340. package/lib/rules/rest-spread-spacing.js +128 -98
  341. package/lib/rules/semi-spacing.js +281 -232
  342. package/lib/rules/semi-style.js +176 -116
  343. package/lib/rules/semi.js +456 -418
  344. package/lib/rules/sort-imports.js +307 -229
  345. package/lib/rules/sort-keys.js +219 -181
  346. package/lib/rules/sort-vars.js +127 -91
  347. package/lib/rules/space-before-blocks.js +199 -171
  348. package/lib/rules/space-before-function-paren.js +186 -148
  349. package/lib/rules/space-in-parens.js +359 -270
  350. package/lib/rules/space-infix-ops.js +237 -183
  351. package/lib/rules/space-unary-ops.js +356 -280
  352. package/lib/rules/spaced-comment.js +363 -301
  353. package/lib/rules/strict.js +266 -229
  354. package/lib/rules/switch-colon-spacing.js +130 -104
  355. package/lib/rules/symbol-description.js +45 -48
  356. package/lib/rules/template-curly-spacing.js +148 -124
  357. package/lib/rules/template-tag-spacing.js +98 -70
  358. package/lib/rules/unicode-bom.js +54 -54
  359. package/lib/rules/use-isnan.js +237 -110
  360. package/lib/rules/utils/ast-utils.js +2139 -1688
  361. package/lib/rules/utils/char-source.js +247 -0
  362. package/lib/rules/utils/fix-tracker.js +99 -88
  363. package/lib/rules/utils/keywords.js +59 -59
  364. package/lib/rules/utils/lazy-loading-rule-map.js +81 -78
  365. package/lib/rules/utils/regular-expressions.js +35 -19
  366. package/lib/rules/utils/unicode/index.js +9 -4
  367. package/lib/rules/utils/unicode/is-combining-character.js +1 -1
  368. package/lib/rules/utils/unicode/is-emoji-modifier.js +1 -1
  369. package/lib/rules/utils/unicode/is-regional-indicator-symbol.js +1 -1
  370. package/lib/rules/utils/unicode/is-surrogate-pair.js +1 -1
  371. package/lib/rules/valid-typeof.js +153 -109
  372. package/lib/rules/vars-on-top.js +152 -144
  373. package/lib/rules/wrap-iife.js +204 -173
  374. package/lib/rules/wrap-regex.js +77 -47
  375. package/lib/rules/yield-star-spacing.js +145 -116
  376. package/lib/rules/yoda.js +283 -274
  377. package/lib/services/parser-service.js +65 -0
  378. package/lib/services/processor-service.js +101 -0
  379. package/lib/services/suppressions-service.js +302 -0
  380. package/lib/services/warning-service.js +98 -0
  381. package/lib/shared/ajv.js +14 -14
  382. package/lib/shared/assert.js +21 -0
  383. package/lib/shared/ast-utils.js +7 -6
  384. package/lib/shared/deep-merge-arrays.js +62 -0
  385. package/lib/shared/directives.js +3 -2
  386. package/lib/shared/flags.js +108 -0
  387. package/lib/shared/logging.js +24 -16
  388. package/lib/shared/naming.js +109 -0
  389. package/lib/shared/option-utils.js +63 -0
  390. package/lib/shared/relative-module-resolver.js +18 -40
  391. package/lib/shared/runtime-info.js +138 -128
  392. package/lib/shared/serialization.js +78 -0
  393. package/lib/shared/severity.js +22 -22
  394. package/lib/shared/stats.js +30 -0
  395. package/lib/shared/string-utils.js +19 -21
  396. package/lib/shared/text-table.js +68 -0
  397. package/lib/shared/translate-cli-options.js +281 -0
  398. package/lib/shared/traverser.js +153 -146
  399. package/lib/types/config-api.d.ts +12 -0
  400. package/lib/types/index.d.ts +1473 -0
  401. package/lib/types/rules.d.ts +5589 -0
  402. package/lib/types/universal.d.ts +6 -0
  403. package/lib/types/use-at-your-own-risk.d.ts +87 -0
  404. package/lib/universal.js +10 -0
  405. package/lib/unsupported-api.js +8 -9
  406. package/messages/all-files-ignored.js +3 -3
  407. package/messages/all-matched-files-ignored.js +21 -0
  408. package/messages/config-file-missing.js +16 -0
  409. package/messages/config-plugin-missing.js +14 -0
  410. package/messages/config-serialize-function.js +30 -0
  411. package/messages/eslintrc-incompat.js +35 -16
  412. package/messages/eslintrc-plugins.js +8 -5
  413. package/messages/extend-config-missing.js +3 -3
  414. package/messages/failed-to-read-json.js +3 -3
  415. package/messages/file-not-found.js +3 -3
  416. package/messages/invalid-rule-options.js +2 -2
  417. package/messages/invalid-rule-severity.js +2 -2
  418. package/messages/no-config-found.js +4 -4
  419. package/messages/plugin-conflict.js +9 -9
  420. package/messages/plugin-invalid.js +4 -4
  421. package/messages/plugin-missing.js +4 -4
  422. package/messages/print-config-with-directory-path.js +2 -2
  423. package/messages/shared.js +6 -1
  424. package/messages/whitespace-found.js +3 -3
  425. package/package.json +105 -60
  426. package/conf/config-schema.js +0 -93
  427. package/lib/cli-engine/formatters/checkstyle.js +0 -60
  428. package/lib/cli-engine/formatters/compact.js +0 -60
  429. package/lib/cli-engine/formatters/jslint-xml.js +0 -41
  430. package/lib/cli-engine/formatters/junit.js +0 -82
  431. package/lib/cli-engine/formatters/tap.js +0 -95
  432. package/lib/cli-engine/formatters/unix.js +0 -58
  433. package/lib/cli-engine/formatters/visualstudio.js +0 -63
  434. package/lib/cli-engine/xml-escape.js +0 -34
  435. package/lib/config/flat-config-helpers.js +0 -111
  436. package/lib/config/rule-validator.js +0 -158
  437. package/lib/eslint/flat-eslint.js +0 -1159
  438. package/lib/linter/config-comment-parser.js +0 -185
  439. package/lib/linter/node-event-generator.js +0 -354
  440. package/lib/linter/report-translator.js +0 -369
  441. package/lib/linter/safe-emitter.js +0 -52
  442. package/lib/rule-tester/flat-rule-tester.js +0 -1131
  443. package/lib/rules/require-jsdoc.js +0 -122
  444. package/lib/rules/utils/patterns/letters.js +0 -36
  445. package/lib/rules/valid-jsdoc.js +0 -516
  446. package/lib/shared/config-validator.js +0 -347
  447. package/lib/shared/deprecation-warnings.js +0 -58
  448. package/lib/shared/types.js +0 -216
  449. package/lib/source-code/index.js +0 -5
  450. package/lib/source-code/source-code.js +0 -1055
  451. package/lib/source-code/token-store/backward-token-comment-cursor.js +0 -57
  452. package/lib/source-code/token-store/backward-token-cursor.js +0 -58
  453. package/lib/source-code/token-store/cursors.js +0 -90
  454. package/lib/source-code/token-store/forward-token-comment-cursor.js +0 -57
  455. package/lib/source-code/token-store/forward-token-cursor.js +0 -63
  456. package/lib/source-code/token-store/index.js +0 -627
  457. package/lib/source-code/token-store/padded-token-cursor.js +0 -38
  458. package/lib/source-code/token-store/utils.js +0 -107
@@ -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,1682 +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: true,
498
- replacedBy: [],
499
- type: "layout",
500
-
501
- docs: {
502
- description: "Enforce consistent indentation",
503
- recommended: false,
504
- url: "https://eslint.org/docs/latest/rules/indent"
505
- },
506
-
507
- fixable: "whitespace",
508
-
509
- schema: [
510
- {
511
- oneOf: [
512
- {
513
- enum: ["tab"]
514
- },
515
- {
516
- type: "integer",
517
- minimum: 0
518
- }
519
- ]
520
- },
521
- {
522
- type: "object",
523
- properties: {
524
- SwitchCase: {
525
- type: "integer",
526
- minimum: 0,
527
- default: 0
528
- },
529
- VariableDeclarator: {
530
- oneOf: [
531
- ELEMENT_LIST_SCHEMA,
532
- {
533
- type: "object",
534
- properties: {
535
- var: ELEMENT_LIST_SCHEMA,
536
- let: ELEMENT_LIST_SCHEMA,
537
- const: ELEMENT_LIST_SCHEMA
538
- },
539
- additionalProperties: false
540
- }
541
- ]
542
- },
543
- outerIIFEBody: {
544
- oneOf: [
545
- {
546
- type: "integer",
547
- minimum: 0
548
- },
549
- {
550
- enum: ["off"]
551
- }
552
- ]
553
- },
554
- MemberExpression: {
555
- oneOf: [
556
- {
557
- type: "integer",
558
- minimum: 0
559
- },
560
- {
561
- enum: ["off"]
562
- }
563
- ]
564
- },
565
- FunctionDeclaration: {
566
- type: "object",
567
- properties: {
568
- parameters: ELEMENT_LIST_SCHEMA,
569
- body: {
570
- type: "integer",
571
- minimum: 0
572
- }
573
- },
574
- additionalProperties: false
575
- },
576
- FunctionExpression: {
577
- type: "object",
578
- properties: {
579
- parameters: ELEMENT_LIST_SCHEMA,
580
- body: {
581
- type: "integer",
582
- minimum: 0
583
- }
584
- },
585
- additionalProperties: false
586
- },
587
- StaticBlock: {
588
- type: "object",
589
- properties: {
590
- body: {
591
- type: "integer",
592
- minimum: 0
593
- }
594
- },
595
- additionalProperties: false
596
- },
597
- CallExpression: {
598
- type: "object",
599
- properties: {
600
- arguments: ELEMENT_LIST_SCHEMA
601
- },
602
- additionalProperties: false
603
- },
604
- ArrayExpression: ELEMENT_LIST_SCHEMA,
605
- ObjectExpression: ELEMENT_LIST_SCHEMA,
606
- ImportDeclaration: ELEMENT_LIST_SCHEMA,
607
- flatTernaryExpressions: {
608
- type: "boolean",
609
- default: false
610
- },
611
- offsetTernaryExpressions: {
612
- type: "boolean",
613
- default: false
614
- },
615
- ignoredNodes: {
616
- type: "array",
617
- items: {
618
- type: "string",
619
- not: {
620
- pattern: ":exit$"
621
- }
622
- }
623
- },
624
- ignoreComments: {
625
- type: "boolean",
626
- default: false
627
- }
628
- },
629
- additionalProperties: false
630
- }
631
- ],
632
- messages: {
633
- wrongIndentation: "Expected indentation of {{expected}} but found {{actual}}."
634
- }
635
- },
636
-
637
- create(context) {
638
- const DEFAULT_VARIABLE_INDENT = 1;
639
- const DEFAULT_PARAMETER_INDENT = 1;
640
- const DEFAULT_FUNCTION_BODY_INDENT = 1;
641
-
642
- let indentType = "space";
643
- let indentSize = 4;
644
- const options = {
645
- SwitchCase: 0,
646
- VariableDeclarator: {
647
- var: DEFAULT_VARIABLE_INDENT,
648
- let: DEFAULT_VARIABLE_INDENT,
649
- const: DEFAULT_VARIABLE_INDENT
650
- },
651
- outerIIFEBody: 1,
652
- FunctionDeclaration: {
653
- parameters: DEFAULT_PARAMETER_INDENT,
654
- body: DEFAULT_FUNCTION_BODY_INDENT
655
- },
656
- FunctionExpression: {
657
- parameters: DEFAULT_PARAMETER_INDENT,
658
- body: DEFAULT_FUNCTION_BODY_INDENT
659
- },
660
- StaticBlock: {
661
- body: DEFAULT_FUNCTION_BODY_INDENT
662
- },
663
- CallExpression: {
664
- arguments: DEFAULT_PARAMETER_INDENT
665
- },
666
- MemberExpression: 1,
667
- ArrayExpression: 1,
668
- ObjectExpression: 1,
669
- ImportDeclaration: 1,
670
- flatTernaryExpressions: false,
671
- ignoredNodes: [],
672
- ignoreComments: false
673
- };
674
-
675
- if (context.options.length) {
676
- if (context.options[0] === "tab") {
677
- indentSize = 1;
678
- indentType = "tab";
679
- } else {
680
- indentSize = context.options[0];
681
- indentType = "space";
682
- }
683
-
684
- if (context.options[1]) {
685
- Object.assign(options, context.options[1]);
686
-
687
- if (typeof options.VariableDeclarator === "number" || options.VariableDeclarator === "first") {
688
- options.VariableDeclarator = {
689
- var: options.VariableDeclarator,
690
- let: options.VariableDeclarator,
691
- const: options.VariableDeclarator
692
- };
693
- }
694
- }
695
- }
696
-
697
- const sourceCode = context.sourceCode;
698
- const tokenInfo = new TokenInfo(sourceCode);
699
- const offsets = new OffsetStorage(tokenInfo, indentSize, indentType === "space" ? " " : "\t", sourceCode.text.length);
700
- const parameterParens = new WeakSet();
701
-
702
- /**
703
- * Creates an error message for a line, given the expected/actual indentation.
704
- * @param {int} expectedAmount The expected amount of indentation characters for this line
705
- * @param {int} actualSpaces The actual number of indentation spaces that were found on this line
706
- * @param {int} actualTabs The actual number of indentation tabs that were found on this line
707
- * @returns {string} An error message for this line
708
- */
709
- function createErrorMessageData(expectedAmount, actualSpaces, actualTabs) {
710
- const expectedStatement = `${expectedAmount} ${indentType}${expectedAmount === 1 ? "" : "s"}`; // e.g. "2 tabs"
711
- const foundSpacesWord = `space${actualSpaces === 1 ? "" : "s"}`; // e.g. "space"
712
- const foundTabsWord = `tab${actualTabs === 1 ? "" : "s"}`; // e.g. "tabs"
713
- let foundStatement;
714
-
715
- if (actualSpaces > 0) {
716
-
717
- /*
718
- * Abbreviate the message if the expected indentation is also spaces.
719
- * e.g. 'Expected 4 spaces but found 2' rather than 'Expected 4 spaces but found 2 spaces'
720
- */
721
- foundStatement = indentType === "space" ? actualSpaces : `${actualSpaces} ${foundSpacesWord}`;
722
- } else if (actualTabs > 0) {
723
- foundStatement = indentType === "tab" ? actualTabs : `${actualTabs} ${foundTabsWord}`;
724
- } else {
725
- foundStatement = "0";
726
- }
727
- return {
728
- expected: expectedStatement,
729
- actual: foundStatement
730
- };
731
- }
732
-
733
- /**
734
- * Reports a given indent violation
735
- * @param {Token} token Token violating the indent rule
736
- * @param {string} neededIndent Expected indentation string
737
- * @returns {void}
738
- */
739
- function report(token, neededIndent) {
740
- const actualIndent = Array.from(tokenInfo.getTokenIndent(token));
741
- const numSpaces = actualIndent.filter(char => char === " ").length;
742
- const numTabs = actualIndent.filter(char => char === "\t").length;
743
-
744
- context.report({
745
- node: token,
746
- messageId: "wrongIndentation",
747
- data: createErrorMessageData(neededIndent.length, numSpaces, numTabs),
748
- loc: {
749
- start: { line: token.loc.start.line, column: 0 },
750
- end: { line: token.loc.start.line, column: token.loc.start.column }
751
- },
752
- fix(fixer) {
753
- const range = [token.range[0] - token.loc.start.column, token.range[0]];
754
- const newText = neededIndent;
755
-
756
- return fixer.replaceTextRange(range, newText);
757
- }
758
- });
759
- }
760
-
761
- /**
762
- * Checks if a token's indentation is correct
763
- * @param {Token} token Token to examine
764
- * @param {string} desiredIndent Desired indentation of the string
765
- * @returns {boolean} `true` if the token's indentation is correct
766
- */
767
- function validateTokenIndent(token, desiredIndent) {
768
- const indentation = tokenInfo.getTokenIndent(token);
769
-
770
- return indentation === desiredIndent ||
771
-
772
- // To avoid conflicts with no-mixed-spaces-and-tabs, don't report mixed spaces and tabs.
773
- indentation.includes(" ") && indentation.includes("\t");
774
- }
775
-
776
- /**
777
- * Check to see if the node is a file level IIFE
778
- * @param {ASTNode} node The function node to check.
779
- * @returns {boolean} True if the node is the outer IIFE
780
- */
781
- function isOuterIIFE(node) {
782
-
783
- /*
784
- * Verify that the node is an IIFE
785
- */
786
- if (!node.parent || node.parent.type !== "CallExpression" || node.parent.callee !== node) {
787
- return false;
788
- }
789
-
790
- /*
791
- * Navigate legal ancestors to determine whether this IIFE is outer.
792
- * A "legal ancestor" is an expression or statement that causes the function to get executed immediately.
793
- * For example, `!(function(){})()` is an outer IIFE even though it is preceded by a ! operator.
794
- */
795
- let statement = node.parent && node.parent.parent;
796
-
797
- while (
798
- statement.type === "UnaryExpression" && ["!", "~", "+", "-"].includes(statement.operator) ||
799
- statement.type === "AssignmentExpression" ||
800
- statement.type === "LogicalExpression" ||
801
- statement.type === "SequenceExpression" ||
802
- statement.type === "VariableDeclarator"
803
- ) {
804
- statement = statement.parent;
805
- }
806
-
807
- return (statement.type === "ExpressionStatement" || statement.type === "VariableDeclaration") && statement.parent.type === "Program";
808
- }
809
-
810
- /**
811
- * Counts the number of linebreaks that follow the last non-whitespace character in a string
812
- * @param {string} string The string to check
813
- * @returns {number} The number of JavaScript linebreaks that follow the last non-whitespace character,
814
- * or the total number of linebreaks if the string is all whitespace.
815
- */
816
- function countTrailingLinebreaks(string) {
817
- const trailingWhitespace = string.match(/\s*$/u)[0];
818
- const linebreakMatches = trailingWhitespace.match(astUtils.createGlobalLinebreakMatcher());
819
-
820
- return linebreakMatches === null ? 0 : linebreakMatches.length;
821
- }
822
-
823
- /**
824
- * Check indentation for lists of elements (arrays, objects, function params)
825
- * @param {ASTNode[]} elements List of elements that should be offset
826
- * @param {Token} startToken The start token of the list that element should be aligned against, e.g. '['
827
- * @param {Token} endToken The end token of the list, e.g. ']'
828
- * @param {number|string} offset The amount that the elements should be offset
829
- * @returns {void}
830
- */
831
- function addElementListIndent(elements, startToken, endToken, offset) {
832
-
833
- /**
834
- * Gets the first token of a given element, including surrounding parentheses.
835
- * @param {ASTNode} element A node in the `elements` list
836
- * @returns {Token} The first token of this element
837
- */
838
- function getFirstToken(element) {
839
- let token = sourceCode.getTokenBefore(element);
840
-
841
- while (astUtils.isOpeningParenToken(token) && token !== startToken) {
842
- token = sourceCode.getTokenBefore(token);
843
- }
844
- return sourceCode.getTokenAfter(token);
845
- }
846
-
847
- // Run through all the tokens in the list, and offset them by one indent level (mainly for comments, other things will end up overridden)
848
- offsets.setDesiredOffsets(
849
- [startToken.range[1], endToken.range[0]],
850
- startToken,
851
- typeof offset === "number" ? offset : 1
852
- );
853
- offsets.setDesiredOffset(endToken, startToken, 0);
854
-
855
- // If the preference is "first" but there is no first element (e.g. sparse arrays w/ empty first slot), fall back to 1 level.
856
- if (offset === "first" && elements.length && !elements[0]) {
857
- return;
858
- }
859
- elements.forEach((element, index) => {
860
- if (!element) {
861
-
862
- // Skip holes in arrays
863
- return;
864
- }
865
- if (offset === "off") {
866
-
867
- // Ignore the first token of every element if the "off" option is used
868
- offsets.ignoreToken(getFirstToken(element));
869
- }
870
-
871
- // Offset the following elements correctly relative to the first element
872
- if (index === 0) {
873
- return;
874
- }
875
- if (offset === "first" && tokenInfo.isFirstTokenOfLine(getFirstToken(element))) {
876
- offsets.matchOffsetOf(getFirstToken(elements[0]), getFirstToken(element));
877
- } else {
878
- const previousElement = elements[index - 1];
879
- const firstTokenOfPreviousElement = previousElement && getFirstToken(previousElement);
880
- const previousElementLastToken = previousElement && sourceCode.getLastToken(previousElement);
881
-
882
- if (
883
- previousElement &&
884
- previousElementLastToken.loc.end.line - countTrailingLinebreaks(previousElementLastToken.value) > startToken.loc.end.line
885
- ) {
886
- offsets.setDesiredOffsets(
887
- [previousElement.range[1], element.range[1]],
888
- firstTokenOfPreviousElement,
889
- 0
890
- );
891
- }
892
- }
893
- });
894
- }
895
-
896
- /**
897
- * Check and decide whether to check for indentation for blockless nodes
898
- * Scenarios are for or while statements without braces around them
899
- * @param {ASTNode} node node to examine
900
- * @returns {void}
901
- */
902
- function addBlocklessNodeIndent(node) {
903
- if (node.type !== "BlockStatement") {
904
- const lastParentToken = sourceCode.getTokenBefore(node, astUtils.isNotOpeningParenToken);
905
-
906
- let firstBodyToken = sourceCode.getFirstToken(node);
907
- let lastBodyToken = sourceCode.getLastToken(node);
908
-
909
- while (
910
- astUtils.isOpeningParenToken(sourceCode.getTokenBefore(firstBodyToken)) &&
911
- astUtils.isClosingParenToken(sourceCode.getTokenAfter(lastBodyToken))
912
- ) {
913
- firstBodyToken = sourceCode.getTokenBefore(firstBodyToken);
914
- lastBodyToken = sourceCode.getTokenAfter(lastBodyToken);
915
- }
916
-
917
- offsets.setDesiredOffsets([firstBodyToken.range[0], lastBodyToken.range[1]], lastParentToken, 1);
918
- }
919
- }
920
-
921
- /**
922
- * Checks the indentation for nodes that are like function calls (`CallExpression` and `NewExpression`)
923
- * @param {ASTNode} node A CallExpression or NewExpression node
924
- * @returns {void}
925
- */
926
- function addFunctionCallIndent(node) {
927
- let openingParen;
928
-
929
- if (node.arguments.length) {
930
- openingParen = sourceCode.getFirstTokenBetween(node.callee, node.arguments[0], astUtils.isOpeningParenToken);
931
- } else {
932
- openingParen = sourceCode.getLastToken(node, 1);
933
- }
934
- const closingParen = sourceCode.getLastToken(node);
935
-
936
- parameterParens.add(openingParen);
937
- parameterParens.add(closingParen);
938
-
939
- /*
940
- * If `?.` token exists, set desired offset for that.
941
- * This logic is copied from `MemberExpression`'s.
942
- */
943
- if (node.optional) {
944
- const dotToken = sourceCode.getTokenAfter(node.callee, astUtils.isQuestionDotToken);
945
- const calleeParenCount = sourceCode.getTokensBetween(node.callee, dotToken, { filter: astUtils.isClosingParenToken }).length;
946
- const firstTokenOfCallee = calleeParenCount
947
- ? sourceCode.getTokenBefore(node.callee, { skip: calleeParenCount - 1 })
948
- : sourceCode.getFirstToken(node.callee);
949
- const lastTokenOfCallee = sourceCode.getTokenBefore(dotToken);
950
- const offsetBase = lastTokenOfCallee.loc.end.line === openingParen.loc.start.line
951
- ? lastTokenOfCallee
952
- : firstTokenOfCallee;
953
-
954
- offsets.setDesiredOffset(dotToken, offsetBase, 1);
955
- }
956
-
957
- const offsetAfterToken = node.callee.type === "TaggedTemplateExpression" ? sourceCode.getFirstToken(node.callee.quasi) : openingParen;
958
- const offsetToken = sourceCode.getTokenBefore(offsetAfterToken);
959
-
960
- offsets.setDesiredOffset(openingParen, offsetToken, 0);
961
-
962
- addElementListIndent(node.arguments, openingParen, closingParen, options.CallExpression.arguments);
963
- }
964
-
965
- /**
966
- * Checks the indentation of parenthesized values, given a list of tokens in a program
967
- * @param {Token[]} tokens A list of tokens
968
- * @returns {void}
969
- */
970
- function addParensIndent(tokens) {
971
- const parenStack = [];
972
- const parenPairs = [];
973
-
974
- for (let i = 0; i < tokens.length; i++) {
975
- const nextToken = tokens[i];
976
-
977
- if (astUtils.isOpeningParenToken(nextToken)) {
978
- parenStack.push(nextToken);
979
- } else if (astUtils.isClosingParenToken(nextToken)) {
980
- parenPairs.push({ left: parenStack.pop(), right: nextToken });
981
- }
982
- }
983
-
984
- for (let i = parenPairs.length - 1; i >= 0; i--) {
985
- const leftParen = parenPairs[i].left;
986
- const rightParen = parenPairs[i].right;
987
-
988
- // We only want to handle parens around expressions, so exclude parentheses that are in function parameters and function call arguments.
989
- if (!parameterParens.has(leftParen) && !parameterParens.has(rightParen)) {
990
- const parenthesizedTokens = new Set(sourceCode.getTokensBetween(leftParen, rightParen));
991
-
992
- parenthesizedTokens.forEach(token => {
993
- if (!parenthesizedTokens.has(offsets.getFirstDependency(token))) {
994
- offsets.setDesiredOffset(token, leftParen, 1);
995
- }
996
- });
997
- }
998
-
999
- offsets.setDesiredOffset(rightParen, leftParen, 0);
1000
- }
1001
- }
1002
-
1003
- /**
1004
- * Ignore all tokens within an unknown node whose offset do not depend
1005
- * on another token's offset within the unknown node
1006
- * @param {ASTNode} node Unknown Node
1007
- * @returns {void}
1008
- */
1009
- function ignoreNode(node) {
1010
- const unknownNodeTokens = new Set(sourceCode.getTokens(node, { includeComments: true }));
1011
-
1012
- unknownNodeTokens.forEach(token => {
1013
- if (!unknownNodeTokens.has(offsets.getFirstDependency(token))) {
1014
- const firstTokenOfLine = tokenInfo.getFirstTokenOfLine(token);
1015
-
1016
- if (token === firstTokenOfLine) {
1017
- offsets.ignoreToken(token);
1018
- } else {
1019
- offsets.setDesiredOffset(token, firstTokenOfLine, 0);
1020
- }
1021
- }
1022
- });
1023
- }
1024
-
1025
- /**
1026
- * Check whether the given token is on the first line of a statement.
1027
- * @param {Token} token The token to check.
1028
- * @param {ASTNode} leafNode The expression node that the token belongs directly.
1029
- * @returns {boolean} `true` if the token is on the first line of a statement.
1030
- */
1031
- function isOnFirstLineOfStatement(token, leafNode) {
1032
- let node = leafNode;
1033
-
1034
- while (node.parent && !node.parent.type.endsWith("Statement") && !node.parent.type.endsWith("Declaration")) {
1035
- node = node.parent;
1036
- }
1037
- node = node.parent;
1038
-
1039
- return !node || node.loc.start.line === token.loc.start.line;
1040
- }
1041
-
1042
- /**
1043
- * Check whether there are any blank (whitespace-only) lines between
1044
- * two tokens on separate lines.
1045
- * @param {Token} firstToken The first token.
1046
- * @param {Token} secondToken The second token.
1047
- * @returns {boolean} `true` if the tokens are on separate lines and
1048
- * there exists a blank line between them, `false` otherwise.
1049
- */
1050
- function hasBlankLinesBetween(firstToken, secondToken) {
1051
- const firstTokenLine = firstToken.loc.end.line;
1052
- const secondTokenLine = secondToken.loc.start.line;
1053
-
1054
- if (firstTokenLine === secondTokenLine || firstTokenLine === secondTokenLine - 1) {
1055
- return false;
1056
- }
1057
-
1058
- for (let line = firstTokenLine + 1; line < secondTokenLine; ++line) {
1059
- if (!tokenInfo.firstTokensByLineNumber.has(line)) {
1060
- return true;
1061
- }
1062
- }
1063
-
1064
- return false;
1065
- }
1066
-
1067
- const ignoredNodeFirstTokens = new Set();
1068
-
1069
- const baseOffsetListeners = {
1070
- "ArrayExpression, ArrayPattern"(node) {
1071
- const openingBracket = sourceCode.getFirstToken(node);
1072
- const closingBracket = sourceCode.getTokenAfter([...node.elements].reverse().find(_ => _) || openingBracket, astUtils.isClosingBracketToken);
1073
-
1074
- addElementListIndent(node.elements, openingBracket, closingBracket, options.ArrayExpression);
1075
- },
1076
-
1077
- "ObjectExpression, ObjectPattern"(node) {
1078
- const openingCurly = sourceCode.getFirstToken(node);
1079
- const closingCurly = sourceCode.getTokenAfter(
1080
- node.properties.length ? node.properties[node.properties.length - 1] : openingCurly,
1081
- astUtils.isClosingBraceToken
1082
- );
1083
-
1084
- addElementListIndent(node.properties, openingCurly, closingCurly, options.ObjectExpression);
1085
- },
1086
-
1087
- ArrowFunctionExpression(node) {
1088
- const maybeOpeningParen = sourceCode.getFirstToken(node, { skip: node.async ? 1 : 0 });
1089
-
1090
- if (astUtils.isOpeningParenToken(maybeOpeningParen)) {
1091
- const openingParen = maybeOpeningParen;
1092
- const closingParen = sourceCode.getTokenBefore(node.body, astUtils.isClosingParenToken);
1093
-
1094
- parameterParens.add(openingParen);
1095
- parameterParens.add(closingParen);
1096
- addElementListIndent(node.params, openingParen, closingParen, options.FunctionExpression.parameters);
1097
- }
1098
-
1099
- addBlocklessNodeIndent(node.body);
1100
- },
1101
-
1102
- AssignmentExpression(node) {
1103
- const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
1104
-
1105
- offsets.setDesiredOffsets([operator.range[0], node.range[1]], sourceCode.getLastToken(node.left), 1);
1106
- offsets.ignoreToken(operator);
1107
- offsets.ignoreToken(sourceCode.getTokenAfter(operator));
1108
- },
1109
-
1110
- "BinaryExpression, LogicalExpression"(node) {
1111
- const operator = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
1112
-
1113
- /*
1114
- * For backwards compatibility, don't check BinaryExpression indents, e.g.
1115
- * var foo = bar &&
1116
- * baz;
1117
- */
1118
-
1119
- const tokenAfterOperator = sourceCode.getTokenAfter(operator);
1120
-
1121
- offsets.ignoreToken(operator);
1122
- offsets.ignoreToken(tokenAfterOperator);
1123
- offsets.setDesiredOffset(tokenAfterOperator, operator, 0);
1124
- },
1125
-
1126
- "BlockStatement, ClassBody"(node) {
1127
- let blockIndentLevel;
1128
-
1129
- if (node.parent && isOuterIIFE(node.parent)) {
1130
- blockIndentLevel = options.outerIIFEBody;
1131
- } else if (node.parent && (node.parent.type === "FunctionExpression" || node.parent.type === "ArrowFunctionExpression")) {
1132
- blockIndentLevel = options.FunctionExpression.body;
1133
- } else if (node.parent && node.parent.type === "FunctionDeclaration") {
1134
- blockIndentLevel = options.FunctionDeclaration.body;
1135
- } else {
1136
- blockIndentLevel = 1;
1137
- }
1138
-
1139
- /*
1140
- * For blocks that aren't lone statements, ensure that the opening curly brace
1141
- * is aligned with the parent.
1142
- */
1143
- if (!astUtils.STATEMENT_LIST_PARENTS.has(node.parent.type)) {
1144
- offsets.setDesiredOffset(sourceCode.getFirstToken(node), sourceCode.getFirstToken(node.parent), 0);
1145
- }
1146
-
1147
- addElementListIndent(node.body, sourceCode.getFirstToken(node), sourceCode.getLastToken(node), blockIndentLevel);
1148
- },
1149
-
1150
- CallExpression: addFunctionCallIndent,
1151
-
1152
- "ClassDeclaration[superClass], ClassExpression[superClass]"(node) {
1153
- const classToken = sourceCode.getFirstToken(node);
1154
- const extendsToken = sourceCode.getTokenBefore(node.superClass, astUtils.isNotOpeningParenToken);
1155
-
1156
- offsets.setDesiredOffsets([extendsToken.range[0], node.body.range[0]], classToken, 1);
1157
- },
1158
-
1159
- ConditionalExpression(node) {
1160
- const firstToken = sourceCode.getFirstToken(node);
1161
-
1162
- // `flatTernaryExpressions` option is for the following style:
1163
- // var a =
1164
- // foo > 0 ? bar :
1165
- // foo < 0 ? baz :
1166
- // /*else*/ qiz ;
1167
- if (!options.flatTernaryExpressions ||
1168
- !astUtils.isTokenOnSameLine(node.test, node.consequent) ||
1169
- isOnFirstLineOfStatement(firstToken, node)
1170
- ) {
1171
- const questionMarkToken = sourceCode.getFirstTokenBetween(node.test, node.consequent, token => token.type === "Punctuator" && token.value === "?");
1172
- const colonToken = sourceCode.getFirstTokenBetween(node.consequent, node.alternate, token => token.type === "Punctuator" && token.value === ":");
1173
-
1174
- const firstConsequentToken = sourceCode.getTokenAfter(questionMarkToken);
1175
- const lastConsequentToken = sourceCode.getTokenBefore(colonToken);
1176
- const firstAlternateToken = sourceCode.getTokenAfter(colonToken);
1177
-
1178
- offsets.setDesiredOffset(questionMarkToken, firstToken, 1);
1179
- offsets.setDesiredOffset(colonToken, firstToken, 1);
1180
-
1181
- offsets.setDesiredOffset(firstConsequentToken, firstToken, firstConsequentToken.type === "Punctuator" &&
1182
- options.offsetTernaryExpressions ? 2 : 1);
1183
-
1184
- /*
1185
- * The alternate and the consequent should usually have the same indentation.
1186
- * If they share part of a line, align the alternate against the first token of the consequent.
1187
- * This allows the alternate to be indented correctly in cases like this:
1188
- * foo ? (
1189
- * bar
1190
- * ) : ( // this '(' is aligned with the '(' above, so it's considered to be aligned with `foo`
1191
- * baz // as a result, `baz` is offset by 1 rather than 2
1192
- * )
1193
- */
1194
- if (lastConsequentToken.loc.end.line === firstAlternateToken.loc.start.line) {
1195
- offsets.setDesiredOffset(firstAlternateToken, firstConsequentToken, 0);
1196
- } else {
1197
-
1198
- /**
1199
- * If the alternate and consequent do not share part of a line, offset the alternate from the first
1200
- * token of the conditional expression. For example:
1201
- * foo ? bar
1202
- * : baz
1203
- *
1204
- * If `baz` were aligned with `bar` rather than being offset by 1 from `foo`, `baz` would end up
1205
- * having no expected indentation.
1206
- */
1207
- offsets.setDesiredOffset(firstAlternateToken, firstToken, firstAlternateToken.type === "Punctuator" &&
1208
- options.offsetTernaryExpressions ? 2 : 1);
1209
- }
1210
- }
1211
- },
1212
-
1213
- "DoWhileStatement, WhileStatement, ForInStatement, ForOfStatement, WithStatement": node => addBlocklessNodeIndent(node.body),
1214
-
1215
- ExportNamedDeclaration(node) {
1216
- if (node.declaration === null) {
1217
- const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
1218
-
1219
- // Indent the specifiers in `export {foo, bar, baz}`
1220
- addElementListIndent(node.specifiers, sourceCode.getFirstToken(node, { skip: 1 }), closingCurly, 1);
1221
-
1222
- if (node.source) {
1223
-
1224
- // Indent everything after and including the `from` token in `export {foo, bar, baz} from 'qux'`
1225
- offsets.setDesiredOffsets([closingCurly.range[1], node.range[1]], sourceCode.getFirstToken(node), 1);
1226
- }
1227
- }
1228
- },
1229
-
1230
- ForStatement(node) {
1231
- const forOpeningParen = sourceCode.getFirstToken(node, 1);
1232
-
1233
- if (node.init) {
1234
- offsets.setDesiredOffsets(node.init.range, forOpeningParen, 1);
1235
- }
1236
- if (node.test) {
1237
- offsets.setDesiredOffsets(node.test.range, forOpeningParen, 1);
1238
- }
1239
- if (node.update) {
1240
- offsets.setDesiredOffsets(node.update.range, forOpeningParen, 1);
1241
- }
1242
- addBlocklessNodeIndent(node.body);
1243
- },
1244
-
1245
- "FunctionDeclaration, FunctionExpression"(node) {
1246
- const closingParen = sourceCode.getTokenBefore(node.body);
1247
- const openingParen = sourceCode.getTokenBefore(node.params.length ? node.params[0] : closingParen);
1248
-
1249
- parameterParens.add(openingParen);
1250
- parameterParens.add(closingParen);
1251
- addElementListIndent(node.params, openingParen, closingParen, options[node.type].parameters);
1252
- },
1253
-
1254
- IfStatement(node) {
1255
- addBlocklessNodeIndent(node.consequent);
1256
- if (node.alternate) {
1257
- addBlocklessNodeIndent(node.alternate);
1258
- }
1259
- },
1260
-
1261
- /*
1262
- * For blockless nodes with semicolon-first style, don't indent the semicolon.
1263
- * e.g.
1264
- * if (foo)
1265
- * bar()
1266
- * ; [1, 2, 3].map(foo)
1267
- *
1268
- * Traversal into the node sets indentation of the semicolon, so we need to override it on exit.
1269
- */
1270
- ":matches(DoWhileStatement, ForStatement, ForInStatement, ForOfStatement, IfStatement, WhileStatement, WithStatement):exit"(node) {
1271
- let nodesToCheck;
1272
-
1273
- if (node.type === "IfStatement") {
1274
- nodesToCheck = [node.consequent];
1275
- if (node.alternate) {
1276
- nodesToCheck.push(node.alternate);
1277
- }
1278
- } else {
1279
- nodesToCheck = [node.body];
1280
- }
1281
-
1282
- for (const nodeToCheck of nodesToCheck) {
1283
- const lastToken = sourceCode.getLastToken(nodeToCheck);
1284
-
1285
- if (astUtils.isSemicolonToken(lastToken)) {
1286
- const tokenBeforeLast = sourceCode.getTokenBefore(lastToken);
1287
- const tokenAfterLast = sourceCode.getTokenAfter(lastToken);
1288
-
1289
- // override indentation of `;` only if its line looks like a semicolon-first style line
1290
- if (
1291
- !astUtils.isTokenOnSameLine(tokenBeforeLast, lastToken) &&
1292
- tokenAfterLast &&
1293
- astUtils.isTokenOnSameLine(lastToken, tokenAfterLast)
1294
- ) {
1295
- offsets.setDesiredOffset(
1296
- lastToken,
1297
- sourceCode.getFirstToken(node),
1298
- 0
1299
- );
1300
- }
1301
- }
1302
- }
1303
- },
1304
-
1305
- ImportDeclaration(node) {
1306
- if (node.specifiers.some(specifier => specifier.type === "ImportSpecifier")) {
1307
- const openingCurly = sourceCode.getFirstToken(node, astUtils.isOpeningBraceToken);
1308
- const closingCurly = sourceCode.getLastToken(node, astUtils.isClosingBraceToken);
1309
-
1310
- addElementListIndent(node.specifiers.filter(specifier => specifier.type === "ImportSpecifier"), openingCurly, closingCurly, options.ImportDeclaration);
1311
- }
1312
-
1313
- const fromToken = sourceCode.getLastToken(node, token => token.type === "Identifier" && token.value === "from");
1314
- const sourceToken = sourceCode.getLastToken(node, token => token.type === "String");
1315
- const semiToken = sourceCode.getLastToken(node, token => token.type === "Punctuator" && token.value === ";");
1316
-
1317
- if (fromToken) {
1318
- const end = semiToken && semiToken.range[1] === sourceToken.range[1] ? node.range[1] : sourceToken.range[1];
1319
-
1320
- offsets.setDesiredOffsets([fromToken.range[0], end], sourceCode.getFirstToken(node), 1);
1321
- }
1322
- },
1323
-
1324
- ImportExpression(node) {
1325
- const openingParen = sourceCode.getFirstToken(node, 1);
1326
- const closingParen = sourceCode.getLastToken(node);
1327
-
1328
- parameterParens.add(openingParen);
1329
- parameterParens.add(closingParen);
1330
- offsets.setDesiredOffset(openingParen, sourceCode.getTokenBefore(openingParen), 0);
1331
-
1332
- addElementListIndent([node.source], openingParen, closingParen, options.CallExpression.arguments);
1333
- },
1334
-
1335
- "MemberExpression, JSXMemberExpression, MetaProperty"(node) {
1336
- const object = node.type === "MetaProperty" ? node.meta : node.object;
1337
- const firstNonObjectToken = sourceCode.getFirstTokenBetween(object, node.property, astUtils.isNotClosingParenToken);
1338
- const secondNonObjectToken = sourceCode.getTokenAfter(firstNonObjectToken);
1339
-
1340
- const objectParenCount = sourceCode.getTokensBetween(object, node.property, { filter: astUtils.isClosingParenToken }).length;
1341
- const firstObjectToken = objectParenCount
1342
- ? sourceCode.getTokenBefore(object, { skip: objectParenCount - 1 })
1343
- : sourceCode.getFirstToken(object);
1344
- const lastObjectToken = sourceCode.getTokenBefore(firstNonObjectToken);
1345
- const firstPropertyToken = node.computed ? firstNonObjectToken : secondNonObjectToken;
1346
-
1347
- if (node.computed) {
1348
-
1349
- // For computed MemberExpressions, match the closing bracket with the opening bracket.
1350
- offsets.setDesiredOffset(sourceCode.getLastToken(node), firstNonObjectToken, 0);
1351
- offsets.setDesiredOffsets(node.property.range, firstNonObjectToken, 1);
1352
- }
1353
-
1354
- /*
1355
- * If the object ends on the same line that the property starts, match against the last token
1356
- * of the object, to ensure that the MemberExpression is not indented.
1357
- *
1358
- * Otherwise, match against the first token of the object, e.g.
1359
- * foo
1360
- * .bar
1361
- * .baz // <-- offset by 1 from `foo`
1362
- */
1363
- const offsetBase = lastObjectToken.loc.end.line === firstPropertyToken.loc.start.line
1364
- ? lastObjectToken
1365
- : firstObjectToken;
1366
-
1367
- if (typeof options.MemberExpression === "number") {
1368
-
1369
- // Match the dot (for non-computed properties) or the opening bracket (for computed properties) against the object.
1370
- offsets.setDesiredOffset(firstNonObjectToken, offsetBase, options.MemberExpression);
1371
-
1372
- /*
1373
- * For computed MemberExpressions, match the first token of the property against the opening bracket.
1374
- * Otherwise, match the first token of the property against the object.
1375
- */
1376
- offsets.setDesiredOffset(secondNonObjectToken, node.computed ? firstNonObjectToken : offsetBase, options.MemberExpression);
1377
- } else {
1378
-
1379
- // If the MemberExpression option is off, ignore the dot and the first token of the property.
1380
- offsets.ignoreToken(firstNonObjectToken);
1381
- offsets.ignoreToken(secondNonObjectToken);
1382
-
1383
- // To ignore the property indentation, ensure that the property tokens depend on the ignored tokens.
1384
- offsets.setDesiredOffset(firstNonObjectToken, offsetBase, 0);
1385
- offsets.setDesiredOffset(secondNonObjectToken, firstNonObjectToken, 0);
1386
- }
1387
- },
1388
-
1389
- NewExpression(node) {
1390
-
1391
- // Only indent the arguments if the NewExpression has parens (e.g. `new Foo(bar)` or `new Foo()`, but not `new Foo`
1392
- if (node.arguments.length > 0 ||
1393
- astUtils.isClosingParenToken(sourceCode.getLastToken(node)) &&
1394
- astUtils.isOpeningParenToken(sourceCode.getLastToken(node, 1))) {
1395
- addFunctionCallIndent(node);
1396
- }
1397
- },
1398
-
1399
- Property(node) {
1400
- if (!node.shorthand && !node.method && node.kind === "init") {
1401
- const colon = sourceCode.getFirstTokenBetween(node.key, node.value, astUtils.isColonToken);
1402
-
1403
- offsets.ignoreToken(sourceCode.getTokenAfter(colon));
1404
- }
1405
- },
1406
-
1407
- PropertyDefinition(node) {
1408
- const firstToken = sourceCode.getFirstToken(node);
1409
- const maybeSemicolonToken = sourceCode.getLastToken(node);
1410
- let keyLastToken = null;
1411
-
1412
- // Indent key.
1413
- if (node.computed) {
1414
- const bracketTokenL = sourceCode.getTokenBefore(node.key, astUtils.isOpeningBracketToken);
1415
- const bracketTokenR = keyLastToken = sourceCode.getTokenAfter(node.key, astUtils.isClosingBracketToken);
1416
- const keyRange = [bracketTokenL.range[1], bracketTokenR.range[0]];
1417
-
1418
- if (bracketTokenL !== firstToken) {
1419
- offsets.setDesiredOffset(bracketTokenL, firstToken, 0);
1420
- }
1421
- offsets.setDesiredOffsets(keyRange, bracketTokenL, 1);
1422
- offsets.setDesiredOffset(bracketTokenR, bracketTokenL, 0);
1423
- } else {
1424
- const idToken = keyLastToken = sourceCode.getFirstToken(node.key);
1425
-
1426
- if (idToken !== firstToken) {
1427
- offsets.setDesiredOffset(idToken, firstToken, 1);
1428
- }
1429
- }
1430
-
1431
- // Indent initializer.
1432
- if (node.value) {
1433
- const eqToken = sourceCode.getTokenBefore(node.value, astUtils.isEqToken);
1434
- const valueToken = sourceCode.getTokenAfter(eqToken);
1435
-
1436
- offsets.setDesiredOffset(eqToken, keyLastToken, 1);
1437
- offsets.setDesiredOffset(valueToken, eqToken, 1);
1438
- if (astUtils.isSemicolonToken(maybeSemicolonToken)) {
1439
- offsets.setDesiredOffset(maybeSemicolonToken, eqToken, 1);
1440
- }
1441
- } else if (astUtils.isSemicolonToken(maybeSemicolonToken)) {
1442
- offsets.setDesiredOffset(maybeSemicolonToken, keyLastToken, 1);
1443
- }
1444
- },
1445
-
1446
- StaticBlock(node) {
1447
- const openingCurly = sourceCode.getFirstToken(node, { skip: 1 }); // skip the `static` token
1448
- const closingCurly = sourceCode.getLastToken(node);
1449
-
1450
- addElementListIndent(node.body, openingCurly, closingCurly, options.StaticBlock.body);
1451
- },
1452
-
1453
- SwitchStatement(node) {
1454
- const openingCurly = sourceCode.getTokenAfter(node.discriminant, astUtils.isOpeningBraceToken);
1455
- const closingCurly = sourceCode.getLastToken(node);
1456
-
1457
- offsets.setDesiredOffsets([openingCurly.range[1], closingCurly.range[0]], openingCurly, options.SwitchCase);
1458
-
1459
- if (node.cases.length) {
1460
- sourceCode.getTokensBetween(
1461
- node.cases[node.cases.length - 1],
1462
- closingCurly,
1463
- { includeComments: true, filter: astUtils.isCommentToken }
1464
- ).forEach(token => offsets.ignoreToken(token));
1465
- }
1466
- },
1467
-
1468
- SwitchCase(node) {
1469
- if (!(node.consequent.length === 1 && node.consequent[0].type === "BlockStatement")) {
1470
- const caseKeyword = sourceCode.getFirstToken(node);
1471
- const tokenAfterCurrentCase = sourceCode.getTokenAfter(node);
1472
-
1473
- offsets.setDesiredOffsets([caseKeyword.range[1], tokenAfterCurrentCase.range[0]], caseKeyword, 1);
1474
- }
1475
- },
1476
-
1477
- TemplateLiteral(node) {
1478
- node.expressions.forEach((expression, index) => {
1479
- const previousQuasi = node.quasis[index];
1480
- const nextQuasi = node.quasis[index + 1];
1481
- const tokenToAlignFrom = previousQuasi.loc.start.line === previousQuasi.loc.end.line
1482
- ? sourceCode.getFirstToken(previousQuasi)
1483
- : null;
1484
-
1485
- offsets.setDesiredOffsets([previousQuasi.range[1], nextQuasi.range[0]], tokenToAlignFrom, 1);
1486
- offsets.setDesiredOffset(sourceCode.getFirstToken(nextQuasi), tokenToAlignFrom, 0);
1487
- });
1488
- },
1489
-
1490
- VariableDeclaration(node) {
1491
- let variableIndent = Object.prototype.hasOwnProperty.call(options.VariableDeclarator, node.kind)
1492
- ? options.VariableDeclarator[node.kind]
1493
- : DEFAULT_VARIABLE_INDENT;
1494
-
1495
- const firstToken = sourceCode.getFirstToken(node),
1496
- lastToken = sourceCode.getLastToken(node);
1497
-
1498
- if (options.VariableDeclarator[node.kind] === "first") {
1499
- if (node.declarations.length > 1) {
1500
- addElementListIndent(
1501
- node.declarations,
1502
- firstToken,
1503
- lastToken,
1504
- "first"
1505
- );
1506
- return;
1507
- }
1508
-
1509
- variableIndent = DEFAULT_VARIABLE_INDENT;
1510
- }
1511
-
1512
- if (node.declarations[node.declarations.length - 1].loc.start.line > node.loc.start.line) {
1513
-
1514
- /*
1515
- * VariableDeclarator indentation is a bit different from other forms of indentation, in that the
1516
- * indentation of an opening bracket sometimes won't match that of a closing bracket. For example,
1517
- * the following indentations are correct:
1518
- *
1519
- * var foo = {
1520
- * ok: true
1521
- * };
1522
- *
1523
- * var foo = {
1524
- * ok: true,
1525
- * },
1526
- * bar = 1;
1527
- *
1528
- * Account for when exiting the AST (after indentations have already been set for the nodes in
1529
- * the declaration) by manually increasing the indentation level of the tokens in this declarator
1530
- * on the same line as the start of the declaration, provided that there are declarators that
1531
- * follow this one.
1532
- */
1533
- offsets.setDesiredOffsets(node.range, firstToken, variableIndent, true);
1534
- } else {
1535
- offsets.setDesiredOffsets(node.range, firstToken, variableIndent);
1536
- }
1537
-
1538
- if (astUtils.isSemicolonToken(lastToken)) {
1539
- offsets.ignoreToken(lastToken);
1540
- }
1541
- },
1542
-
1543
- VariableDeclarator(node) {
1544
- if (node.init) {
1545
- const equalOperator = sourceCode.getTokenBefore(node.init, astUtils.isNotOpeningParenToken);
1546
- const tokenAfterOperator = sourceCode.getTokenAfter(equalOperator);
1547
-
1548
- offsets.ignoreToken(equalOperator);
1549
- offsets.ignoreToken(tokenAfterOperator);
1550
- offsets.setDesiredOffsets([tokenAfterOperator.range[0], node.range[1]], equalOperator, 1);
1551
- offsets.setDesiredOffset(equalOperator, sourceCode.getLastToken(node.id), 0);
1552
- }
1553
- },
1554
-
1555
- "JSXAttribute[value]"(node) {
1556
- const equalsToken = sourceCode.getFirstTokenBetween(node.name, node.value, token => token.type === "Punctuator" && token.value === "=");
1557
-
1558
- offsets.setDesiredOffsets([equalsToken.range[0], node.value.range[1]], sourceCode.getFirstToken(node.name), 1);
1559
- },
1560
-
1561
- JSXElement(node) {
1562
- if (node.closingElement) {
1563
- addElementListIndent(node.children, sourceCode.getFirstToken(node.openingElement), sourceCode.getFirstToken(node.closingElement), 1);
1564
- }
1565
- },
1566
-
1567
- JSXOpeningElement(node) {
1568
- const firstToken = sourceCode.getFirstToken(node);
1569
- let closingToken;
1570
-
1571
- if (node.selfClosing) {
1572
- closingToken = sourceCode.getLastToken(node, { skip: 1 });
1573
- offsets.setDesiredOffset(sourceCode.getLastToken(node), closingToken, 0);
1574
- } else {
1575
- closingToken = sourceCode.getLastToken(node);
1576
- }
1577
- offsets.setDesiredOffsets(node.name.range, sourceCode.getFirstToken(node));
1578
- addElementListIndent(node.attributes, firstToken, closingToken, 1);
1579
- },
1580
-
1581
- JSXClosingElement(node) {
1582
- const firstToken = sourceCode.getFirstToken(node);
1583
-
1584
- offsets.setDesiredOffsets(node.name.range, firstToken, 1);
1585
- },
1586
-
1587
- JSXFragment(node) {
1588
- const firstOpeningToken = sourceCode.getFirstToken(node.openingFragment);
1589
- const firstClosingToken = sourceCode.getFirstToken(node.closingFragment);
1590
-
1591
- addElementListIndent(node.children, firstOpeningToken, firstClosingToken, 1);
1592
- },
1593
-
1594
- JSXOpeningFragment(node) {
1595
- const firstToken = sourceCode.getFirstToken(node);
1596
- const closingToken = sourceCode.getLastToken(node);
1597
-
1598
- offsets.setDesiredOffsets(node.range, firstToken, 1);
1599
- offsets.matchOffsetOf(firstToken, closingToken);
1600
- },
1601
-
1602
- JSXClosingFragment(node) {
1603
- const firstToken = sourceCode.getFirstToken(node);
1604
- const slashToken = sourceCode.getLastToken(node, { skip: 1 });
1605
- const closingToken = sourceCode.getLastToken(node);
1606
- const tokenToMatch = astUtils.isTokenOnSameLine(slashToken, closingToken) ? slashToken : closingToken;
1607
-
1608
- offsets.setDesiredOffsets(node.range, firstToken, 1);
1609
- offsets.matchOffsetOf(firstToken, tokenToMatch);
1610
- },
1611
-
1612
- JSXExpressionContainer(node) {
1613
- const openingCurly = sourceCode.getFirstToken(node);
1614
- const closingCurly = sourceCode.getLastToken(node);
1615
-
1616
- offsets.setDesiredOffsets(
1617
- [openingCurly.range[1], closingCurly.range[0]],
1618
- openingCurly,
1619
- 1
1620
- );
1621
- },
1622
-
1623
- JSXSpreadAttribute(node) {
1624
- const openingCurly = sourceCode.getFirstToken(node);
1625
- const closingCurly = sourceCode.getLastToken(node);
1626
-
1627
- offsets.setDesiredOffsets(
1628
- [openingCurly.range[1], closingCurly.range[0]],
1629
- openingCurly,
1630
- 1
1631
- );
1632
- },
1633
-
1634
- "*"(node) {
1635
- const firstToken = sourceCode.getFirstToken(node);
1636
-
1637
- // Ensure that the children of every node are indented at least as much as the first token.
1638
- if (firstToken && !ignoredNodeFirstTokens.has(firstToken)) {
1639
- offsets.setDesiredOffsets(node.range, firstToken, 0);
1640
- }
1641
- }
1642
- };
1643
-
1644
- const listenerCallQueue = [];
1645
-
1646
- /*
1647
- * To ignore the indentation of a node:
1648
- * 1. Don't call the node's listener when entering it (if it has a listener)
1649
- * 2. Don't set any offsets against the first token of the node.
1650
- * 3. Call `ignoreNode` on the node sometime after exiting it and before validating offsets.
1651
- */
1652
- const offsetListeners = {};
1653
-
1654
- for (const [selector, listener] of Object.entries(baseOffsetListeners)) {
1655
-
1656
- /*
1657
- * Offset listener calls are deferred until traversal is finished, and are called as
1658
- * part of the final `Program:exit` listener. This is necessary because a node might
1659
- * be matched by multiple selectors.
1660
- *
1661
- * Example: Suppose there is an offset listener for `Identifier`, and the user has
1662
- * specified in configuration that `MemberExpression > Identifier` should be ignored.
1663
- * Due to selector specificity rules, the `Identifier` listener will get called first. However,
1664
- * if a given Identifier node is supposed to be ignored, then the `Identifier` offset listener
1665
- * should not have been called at all. Without doing extra selector matching, we don't know
1666
- * whether the Identifier matches the `MemberExpression > Identifier` selector until the
1667
- * `MemberExpression > Identifier` listener is called.
1668
- *
1669
- * To avoid this, the `Identifier` listener isn't called until traversal finishes and all
1670
- * ignored nodes are known.
1671
- */
1672
- offsetListeners[selector] = node => listenerCallQueue.push({ listener, node });
1673
- }
1674
-
1675
- // For each ignored node selector, set up a listener to collect it into the `ignoredNodes` set.
1676
- const ignoredNodes = new Set();
1677
-
1678
- /**
1679
- * Ignores a node
1680
- * @param {ASTNode} node The node to ignore
1681
- * @returns {void}
1682
- */
1683
- function addToIgnoredNodes(node) {
1684
- ignoredNodes.add(node);
1685
- ignoredNodeFirstTokens.add(sourceCode.getFirstToken(node));
1686
- }
1687
-
1688
- const ignoredNodeListeners = options.ignoredNodes.reduce(
1689
- (listeners, ignoredSelector) => Object.assign(listeners, { [ignoredSelector]: addToIgnoredNodes }),
1690
- {}
1691
- );
1692
-
1693
- /*
1694
- * Join the listeners, and add a listener to verify that all tokens actually have the correct indentation
1695
- * at the end.
1696
- *
1697
- * Using Object.assign will cause some offset listeners to be overwritten if the same selector also appears
1698
- * in `ignoredNodeListeners`. This isn't a problem because all of the matching nodes will be ignored,
1699
- * so those listeners wouldn't be called anyway.
1700
- */
1701
- return Object.assign(
1702
- offsetListeners,
1703
- ignoredNodeListeners,
1704
- {
1705
- "*:exit"(node) {
1706
-
1707
- // If a node's type is nonstandard, we can't tell how its children should be offset, so ignore it.
1708
- if (!KNOWN_NODES.has(node.type)) {
1709
- addToIgnoredNodes(node);
1710
- }
1711
- },
1712
- "Program:exit"() {
1713
-
1714
- // If ignoreComments option is enabled, ignore all comment tokens.
1715
- if (options.ignoreComments) {
1716
- sourceCode.getAllComments()
1717
- .forEach(comment => offsets.ignoreToken(comment));
1718
- }
1719
-
1720
- // Invoke the queued offset listeners for the nodes that aren't ignored.
1721
- for (let i = 0; i < listenerCallQueue.length; i++) {
1722
- const nodeInfo = listenerCallQueue[i];
1723
-
1724
- if (!ignoredNodes.has(nodeInfo.node)) {
1725
- nodeInfo.listener(nodeInfo.node);
1726
- }
1727
- }
1728
-
1729
- // Update the offsets for ignored nodes to prevent their child tokens from being reported.
1730
- ignoredNodes.forEach(ignoreNode);
1731
-
1732
- addParensIndent(sourceCode.ast.tokens);
1733
-
1734
- /*
1735
- * Create a Map from (tokenOrComment) => (precedingToken).
1736
- * This is necessary because sourceCode.getTokenBefore does not handle a comment as an argument correctly.
1737
- */
1738
- const precedingTokens = new WeakMap();
1739
-
1740
- for (let i = 0; i < sourceCode.ast.comments.length; i++) {
1741
- const comment = sourceCode.ast.comments[i];
1742
-
1743
- const tokenOrCommentBefore = sourceCode.getTokenBefore(comment, { includeComments: true });
1744
- const hasToken = precedingTokens.has(tokenOrCommentBefore) ? precedingTokens.get(tokenOrCommentBefore) : tokenOrCommentBefore;
1745
-
1746
- precedingTokens.set(comment, hasToken);
1747
- }
1748
-
1749
- for (let i = 1; i < sourceCode.lines.length + 1; i++) {
1750
-
1751
- if (!tokenInfo.firstTokensByLineNumber.has(i)) {
1752
-
1753
- // Don't check indentation on blank lines
1754
- continue;
1755
- }
1756
-
1757
- const firstTokenOfLine = tokenInfo.firstTokensByLineNumber.get(i);
1758
-
1759
- if (firstTokenOfLine.loc.start.line !== i) {
1760
-
1761
- // Don't check the indentation of multi-line tokens (e.g. template literals or block comments) twice.
1762
- continue;
1763
- }
1764
-
1765
- if (astUtils.isCommentToken(firstTokenOfLine)) {
1766
- const tokenBefore = precedingTokens.get(firstTokenOfLine);
1767
- const tokenAfter = tokenBefore ? sourceCode.getTokenAfter(tokenBefore) : sourceCode.ast.tokens[0];
1768
- const mayAlignWithBefore = tokenBefore && !hasBlankLinesBetween(tokenBefore, firstTokenOfLine);
1769
- const mayAlignWithAfter = tokenAfter && !hasBlankLinesBetween(firstTokenOfLine, tokenAfter);
1770
-
1771
- /*
1772
- * If a comment precedes a line that begins with a semicolon token, align to that token, i.e.
1773
- *
1774
- * let foo
1775
- * // comment
1776
- * ;(async () => {})()
1777
- */
1778
- if (tokenAfter && astUtils.isSemicolonToken(tokenAfter) && !astUtils.isTokenOnSameLine(firstTokenOfLine, tokenAfter)) {
1779
- offsets.setDesiredOffset(firstTokenOfLine, tokenAfter, 0);
1780
- }
1781
-
1782
- // If a comment matches the expected indentation of the token immediately before or after, don't report it.
1783
- if (
1784
- mayAlignWithBefore && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenBefore)) ||
1785
- mayAlignWithAfter && validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(tokenAfter))
1786
- ) {
1787
- continue;
1788
- }
1789
- }
1790
-
1791
- // If the token matches the expected indentation, don't report it.
1792
- if (validateTokenIndent(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine))) {
1793
- continue;
1794
- }
1795
-
1796
- // Otherwise, report the token/comment.
1797
- report(firstTokenOfLine, offsets.getDesiredIndent(firstTokenOfLine));
1798
- }
1799
- }
1800
- }
1801
- );
1802
- }
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: "11.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",
523
+ url: "https://eslint.style",
524
+ },
525
+ rule: {
526
+ name: "indent",
527
+ url: "https://eslint.style/rules/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 {number} expectedAmount The expected amount of indentation characters for this line
747
+ * @param {number} actualSpaces The actual number of indentation spaces that were found on this line
748
+ * @param {number} 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
+ },
1803
2334
  };