bahlint 28.58.6934

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 (420) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +370 -0
  3. package/bin/eslint.js +195 -0
  4. package/conf/ecma-version.js +16 -0
  5. package/conf/globals.js +169 -0
  6. package/conf/replacements.json +26 -0
  7. package/conf/rule-type-list.json +91 -0
  8. package/lib/api.js +39 -0
  9. package/lib/cli-engine/formatters/formatters-meta.json +22 -0
  10. package/lib/cli-engine/formatters/gasoline.js +168 -0
  11. package/lib/cli-engine/formatters/html.js +359 -0
  12. package/lib/cli-engine/formatters/json-with-metadata.js +16 -0
  13. package/lib/cli-engine/formatters/json.js +13 -0
  14. package/lib/cli-engine/formatters/stylish.js +153 -0
  15. package/lib/cli-engine/hash.js +35 -0
  16. package/lib/cli-engine/lint-result-cache.js +220 -0
  17. package/lib/cli.js +607 -0
  18. package/lib/config/config-loader.js +683 -0
  19. package/lib/config/config.js +674 -0
  20. package/lib/config/default-config.js +78 -0
  21. package/lib/config/flat-config-array.js +217 -0
  22. package/lib/config/flat-config-schema.js +598 -0
  23. package/lib/config-api.js +12 -0
  24. package/lib/eslint/eslint-helpers.js +1462 -0
  25. package/lib/eslint/eslint.js +1364 -0
  26. package/lib/eslint/index.js +7 -0
  27. package/lib/eslint/worker.js +173 -0
  28. package/lib/languages/js/index.js +336 -0
  29. package/lib/languages/js/source-code/index.js +7 -0
  30. package/lib/languages/js/source-code/source-code.js +1178 -0
  31. package/lib/languages/js/source-code/token-store/backward-token-comment-cursor.js +61 -0
  32. package/lib/languages/js/source-code/token-store/backward-token-cursor.js +57 -0
  33. package/lib/languages/js/source-code/token-store/cursor.js +76 -0
  34. package/lib/languages/js/source-code/token-store/cursors.js +120 -0
  35. package/lib/languages/js/source-code/token-store/decorative-cursor.js +38 -0
  36. package/lib/languages/js/source-code/token-store/filter-cursor.js +42 -0
  37. package/lib/languages/js/source-code/token-store/forward-token-comment-cursor.js +65 -0
  38. package/lib/languages/js/source-code/token-store/forward-token-cursor.js +62 -0
  39. package/lib/languages/js/source-code/token-store/index.js +695 -0
  40. package/lib/languages/js/source-code/token-store/limit-cursor.js +39 -0
  41. package/lib/languages/js/source-code/token-store/padded-token-cursor.js +45 -0
  42. package/lib/languages/js/source-code/token-store/skip-cursor.js +41 -0
  43. package/lib/languages/js/source-code/token-store/utils.js +131 -0
  44. package/lib/languages/js/validate-language-options.js +196 -0
  45. package/lib/linter/apply-disable-directives.js +583 -0
  46. package/lib/linter/code-path-analysis/code-path-analyzer.js +828 -0
  47. package/lib/linter/code-path-analysis/code-path-segment.js +262 -0
  48. package/lib/linter/code-path-analysis/code-path-state.js +2370 -0
  49. package/lib/linter/code-path-analysis/code-path.js +332 -0
  50. package/lib/linter/code-path-analysis/debug-helpers.js +223 -0
  51. package/lib/linter/code-path-analysis/fork-context.js +374 -0
  52. package/lib/linter/code-path-analysis/id-generator.js +44 -0
  53. package/lib/linter/esquery.js +332 -0
  54. package/lib/linter/file-context.js +88 -0
  55. package/lib/linter/file-report.js +604 -0
  56. package/lib/linter/index.js +11 -0
  57. package/lib/linter/interpolate.js +50 -0
  58. package/lib/linter/linter.js +1614 -0
  59. package/lib/linter/rule-fixer.js +199 -0
  60. package/lib/linter/source-code-fixer.js +154 -0
  61. package/lib/linter/source-code-traverser.js +333 -0
  62. package/lib/linter/source-code-visitor.js +81 -0
  63. package/lib/linter/timing.js +209 -0
  64. package/lib/linter/vfile.js +115 -0
  65. package/lib/options.js +416 -0
  66. package/lib/rule-tester/index.js +7 -0
  67. package/lib/rule-tester/rule-tester.js +1817 -0
  68. package/lib/rules/accessor-pairs.js +420 -0
  69. package/lib/rules/array-bracket-newline.js +291 -0
  70. package/lib/rules/array-bracket-spacing.js +301 -0
  71. package/lib/rules/array-callback-return.js +493 -0
  72. package/lib/rules/array-element-newline.js +374 -0
  73. package/lib/rules/arrow-body-style.js +418 -0
  74. package/lib/rules/arrow-parens.js +237 -0
  75. package/lib/rules/arrow-spacing.js +188 -0
  76. package/lib/rules/block-scoped-var.js +137 -0
  77. package/lib/rules/block-spacing.js +202 -0
  78. package/lib/rules/brace-style.js +278 -0
  79. package/lib/rules/callback-return.js +216 -0
  80. package/lib/rules/camelcase.js +422 -0
  81. package/lib/rules/capitalized-comments.js +325 -0
  82. package/lib/rules/class-methods-use-this.js +250 -0
  83. package/lib/rules/comma-dangle.js +424 -0
  84. package/lib/rules/comma-spacing.js +205 -0
  85. package/lib/rules/comma-style.js +391 -0
  86. package/lib/rules/complexity.js +201 -0
  87. package/lib/rules/computed-property-spacing.js +251 -0
  88. package/lib/rules/consistent-return.js +221 -0
  89. package/lib/rules/consistent-this.js +179 -0
  90. package/lib/rules/constructor-super.js +453 -0
  91. package/lib/rules/curly.js +425 -0
  92. package/lib/rules/default-case-last.js +51 -0
  93. package/lib/rules/default-case.js +103 -0
  94. package/lib/rules/default-param-last.js +78 -0
  95. package/lib/rules/dot-location.js +138 -0
  96. package/lib/rules/dot-notation.js +216 -0
  97. package/lib/rules/eol-last.js +135 -0
  98. package/lib/rules/eqeqeq.js +210 -0
  99. package/lib/rules/for-direction.js +168 -0
  100. package/lib/rules/func-call-spacing.js +281 -0
  101. package/lib/rules/func-name-matching.js +338 -0
  102. package/lib/rules/func-names.js +194 -0
  103. package/lib/rules/func-style.js +221 -0
  104. package/lib/rules/function-call-argument-newline.js +166 -0
  105. package/lib/rules/function-paren-newline.js +368 -0
  106. package/lib/rules/generator-star-spacing.js +246 -0
  107. package/lib/rules/getter-return.js +242 -0
  108. package/lib/rules/global-require.js +117 -0
  109. package/lib/rules/grouped-accessor-pairs.js +268 -0
  110. package/lib/rules/guard-for-in.js +85 -0
  111. package/lib/rules/handle-callback-err.js +122 -0
  112. package/lib/rules/id-blacklist.js +241 -0
  113. package/lib/rules/id-denylist.js +223 -0
  114. package/lib/rules/id-length.js +217 -0
  115. package/lib/rules/id-match.js +363 -0
  116. package/lib/rules/implicit-arrow-linebreak.js +125 -0
  117. package/lib/rules/indent-legacy.js +1369 -0
  118. package/lib/rules/indent.js +2334 -0
  119. package/lib/rules/index.js +332 -0
  120. package/lib/rules/init-declarations.js +172 -0
  121. package/lib/rules/jsx-quotes.js +128 -0
  122. package/lib/rules/key-spacing.js +822 -0
  123. package/lib/rules/keyword-spacing.js +701 -0
  124. package/lib/rules/line-comment-position.js +157 -0
  125. package/lib/rules/linebreak-style.js +135 -0
  126. package/lib/rules/lines-around-comment.js +581 -0
  127. package/lib/rules/lines-around-directive.js +249 -0
  128. package/lib/rules/lines-between-class-members.js +358 -0
  129. package/lib/rules/logical-assignment-operators.js +688 -0
  130. package/lib/rules/max-classes-per-file.js +90 -0
  131. package/lib/rules/max-depth.js +159 -0
  132. package/lib/rules/max-len.js +497 -0
  133. package/lib/rules/max-lines-per-function.js +238 -0
  134. package/lib/rules/max-lines.js +189 -0
  135. package/lib/rules/max-nested-callbacks.js +115 -0
  136. package/lib/rules/max-params.js +148 -0
  137. package/lib/rules/max-statements-per-line.js +224 -0
  138. package/lib/rules/max-statements.js +188 -0
  139. package/lib/rules/multiline-comment-style.js +652 -0
  140. package/lib/rules/multiline-ternary.js +257 -0
  141. package/lib/rules/new-cap.js +277 -0
  142. package/lib/rules/new-parens.js +120 -0
  143. package/lib/rules/newline-after-var.js +307 -0
  144. package/lib/rules/newline-before-return.js +242 -0
  145. package/lib/rules/newline-per-chained-call.js +159 -0
  146. package/lib/rules/no-alert.js +149 -0
  147. package/lib/rules/no-array-constructor.js +195 -0
  148. package/lib/rules/no-async-promise-executor.js +45 -0
  149. package/lib/rules/no-await-in-loop.js +115 -0
  150. package/lib/rules/no-bitwise.js +145 -0
  151. package/lib/rules/no-buffer-constructor.js +74 -0
  152. package/lib/rules/no-caller.js +52 -0
  153. package/lib/rules/no-case-declarations.js +80 -0
  154. package/lib/rules/no-catch-shadow.js +96 -0
  155. package/lib/rules/no-class-assign.js +66 -0
  156. package/lib/rules/no-compare-neg-zero.js +74 -0
  157. package/lib/rules/no-cond-assign.js +175 -0
  158. package/lib/rules/no-confusing-arrow.js +127 -0
  159. package/lib/rules/no-console.js +221 -0
  160. package/lib/rules/no-const-assign.js +73 -0
  161. package/lib/rules/no-constant-binary-expression.js +603 -0
  162. package/lib/rules/no-constant-condition.js +177 -0
  163. package/lib/rules/no-constructor-return.js +62 -0
  164. package/lib/rules/no-continue.js +38 -0
  165. package/lib/rules/no-control-regex.js +142 -0
  166. package/lib/rules/no-debugger.js +41 -0
  167. package/lib/rules/no-delete-var.js +42 -0
  168. package/lib/rules/no-div-regex.js +60 -0
  169. package/lib/rules/no-dupe-args.js +92 -0
  170. package/lib/rules/no-dupe-class-members.js +117 -0
  171. package/lib/rules/no-dupe-else-if.js +145 -0
  172. package/lib/rules/no-dupe-keys.js +165 -0
  173. package/lib/rules/no-duplicate-case.js +78 -0
  174. package/lib/rules/no-duplicate-imports.js +368 -0
  175. package/lib/rules/no-else-return.js +450 -0
  176. package/lib/rules/no-empty-character-class.js +83 -0
  177. package/lib/rules/no-empty-function.js +236 -0
  178. package/lib/rules/no-empty-pattern.js +85 -0
  179. package/lib/rules/no-empty-static-block.js +73 -0
  180. package/lib/rules/no-empty.js +153 -0
  181. package/lib/rules/no-eq-null.js +51 -0
  182. package/lib/rules/no-eval.js +295 -0
  183. package/lib/rules/no-ex-assign.js +57 -0
  184. package/lib/rules/no-extend-native.js +180 -0
  185. package/lib/rules/no-extra-bind.js +224 -0
  186. package/lib/rules/no-extra-boolean-cast.js +420 -0
  187. package/lib/rules/no-extra-label.js +169 -0
  188. package/lib/rules/no-extra-parens.js +1669 -0
  189. package/lib/rules/no-extra-semi.js +167 -0
  190. package/lib/rules/no-fallthrough.js +260 -0
  191. package/lib/rules/no-floating-decimal.js +99 -0
  192. package/lib/rules/no-func-assign.js +77 -0
  193. package/lib/rules/no-global-assign.js +101 -0
  194. package/lib/rules/no-implicit-coercion.js +468 -0
  195. package/lib/rules/no-implicit-globals.js +187 -0
  196. package/lib/rules/no-implied-eval.js +170 -0
  197. package/lib/rules/no-import-assign.js +227 -0
  198. package/lib/rules/no-inline-comments.js +115 -0
  199. package/lib/rules/no-inner-declarations.js +147 -0
  200. package/lib/rules/no-invalid-regexp.js +244 -0
  201. package/lib/rules/no-invalid-this.js +178 -0
  202. package/lib/rules/no-irregular-whitespace.js +292 -0
  203. package/lib/rules/no-iterator.js +48 -0
  204. package/lib/rules/no-label-var.js +78 -0
  205. package/lib/rules/no-labels.js +156 -0
  206. package/lib/rules/no-lone-blocks.js +140 -0
  207. package/lib/rules/no-lonely-if.js +126 -0
  208. package/lib/rules/no-loop-func.js +267 -0
  209. package/lib/rules/no-loss-of-precision.js +249 -0
  210. package/lib/rules/no-magic-numbers.js +365 -0
  211. package/lib/rules/no-misleading-character-class.js +595 -0
  212. package/lib/rules/no-mixed-operators.js +253 -0
  213. package/lib/rules/no-mixed-requires.js +267 -0
  214. package/lib/rules/no-mixed-spaces-and-tabs.js +148 -0
  215. package/lib/rules/no-multi-assign.js +66 -0
  216. package/lib/rules/no-multi-spaces.js +179 -0
  217. package/lib/rules/no-multi-str.js +67 -0
  218. package/lib/rules/no-multiple-empty-lines.js +210 -0
  219. package/lib/rules/no-native-reassign.js +114 -0
  220. package/lib/rules/no-negated-condition.js +100 -0
  221. package/lib/rules/no-negated-in-lhs.js +59 -0
  222. package/lib/rules/no-nested-ternary.js +46 -0
  223. package/lib/rules/no-new-func.js +96 -0
  224. package/lib/rules/no-new-native-nonconstructor.js +70 -0
  225. package/lib/rules/no-new-object.js +76 -0
  226. package/lib/rules/no-new-require.js +67 -0
  227. package/lib/rules/no-new-symbol.js +74 -0
  228. package/lib/rules/no-new-wrappers.js +62 -0
  229. package/lib/rules/no-new.js +42 -0
  230. package/lib/rules/no-nonoctal-decimal-escape.js +176 -0
  231. package/lib/rules/no-obj-calls.js +99 -0
  232. package/lib/rules/no-object-constructor.js +124 -0
  233. package/lib/rules/no-octal-escape.js +53 -0
  234. package/lib/rules/no-octal.js +42 -0
  235. package/lib/rules/no-param-reassign.js +248 -0
  236. package/lib/rules/no-path-concat.js +79 -0
  237. package/lib/rules/no-plusplus.js +102 -0
  238. package/lib/rules/no-process-env.js +68 -0
  239. package/lib/rules/no-process-exit.js +67 -0
  240. package/lib/rules/no-promise-executor-return.js +264 -0
  241. package/lib/rules/no-proto.js +45 -0
  242. package/lib/rules/no-prototype-builtins.js +181 -0
  243. package/lib/rules/no-redeclare.js +173 -0
  244. package/lib/rules/no-regex-spaces.js +219 -0
  245. package/lib/rules/no-restricted-exports.js +227 -0
  246. package/lib/rules/no-restricted-globals.js +266 -0
  247. package/lib/rules/no-restricted-imports.js +892 -0
  248. package/lib/rules/no-restricted-modules.js +249 -0
  249. package/lib/rules/no-restricted-properties.js +233 -0
  250. package/lib/rules/no-restricted-syntax.js +74 -0
  251. package/lib/rules/no-return-assign.js +87 -0
  252. package/lib/rules/no-return-await.js +162 -0
  253. package/lib/rules/no-script-url.js +68 -0
  254. package/lib/rules/no-self-assign.js +186 -0
  255. package/lib/rules/no-self-compare.js +77 -0
  256. package/lib/rules/no-sequences.js +158 -0
  257. package/lib/rules/no-setter-return.js +224 -0
  258. package/lib/rules/no-shadow-restricted-names.js +113 -0
  259. package/lib/rules/no-shadow.js +624 -0
  260. package/lib/rules/no-spaced-func.js +105 -0
  261. package/lib/rules/no-sparse-arrays.js +68 -0
  262. package/lib/rules/no-sync.js +81 -0
  263. package/lib/rules/no-tabs.js +110 -0
  264. package/lib/rules/no-template-curly-in-string.js +45 -0
  265. package/lib/rules/no-ternary.js +38 -0
  266. package/lib/rules/no-this-before-super.js +365 -0
  267. package/lib/rules/no-throw-literal.js +46 -0
  268. package/lib/rules/no-trailing-spaces.js +227 -0
  269. package/lib/rules/no-unassigned-vars.js +80 -0
  270. package/lib/rules/no-undef-init.js +101 -0
  271. package/lib/rules/no-undef.js +84 -0
  272. package/lib/rules/no-undefined.js +85 -0
  273. package/lib/rules/no-underscore-dangle.js +383 -0
  274. package/lib/rules/no-unexpected-multiline.js +130 -0
  275. package/lib/rules/no-unmodified-loop-condition.js +360 -0
  276. package/lib/rules/no-unneeded-ternary.js +232 -0
  277. package/lib/rules/no-unreachable-loop.js +190 -0
  278. package/lib/rules/no-unreachable.js +300 -0
  279. package/lib/rules/no-unsafe-finally.js +119 -0
  280. package/lib/rules/no-unsafe-negation.js +152 -0
  281. package/lib/rules/no-unsafe-optional-chaining.js +221 -0
  282. package/lib/rules/no-unused-expressions.js +227 -0
  283. package/lib/rules/no-unused-labels.js +158 -0
  284. package/lib/rules/no-unused-private-class-members.js +219 -0
  285. package/lib/rules/no-unused-vars.js +1739 -0
  286. package/lib/rules/no-use-before-define.js +446 -0
  287. package/lib/rules/no-useless-assignment.js +657 -0
  288. package/lib/rules/no-useless-backreference.js +263 -0
  289. package/lib/rules/no-useless-call.js +95 -0
  290. package/lib/rules/no-useless-catch.js +57 -0
  291. package/lib/rules/no-useless-computed-key.js +204 -0
  292. package/lib/rules/no-useless-concat.js +121 -0
  293. package/lib/rules/no-useless-constructor.js +262 -0
  294. package/lib/rules/no-useless-escape.js +406 -0
  295. package/lib/rules/no-useless-rename.js +202 -0
  296. package/lib/rules/no-useless-return.js +401 -0
  297. package/lib/rules/no-var.js +367 -0
  298. package/lib/rules/no-void.js +69 -0
  299. package/lib/rules/no-warning-comments.js +209 -0
  300. package/lib/rules/no-whitespace-before-property.js +150 -0
  301. package/lib/rules/no-with.js +37 -0
  302. package/lib/rules/nonblock-statement-body-position.js +164 -0
  303. package/lib/rules/object-curly-newline.js +383 -0
  304. package/lib/rules/object-curly-spacing.js +369 -0
  305. package/lib/rules/object-property-newline.js +151 -0
  306. package/lib/rules/object-shorthand.js +652 -0
  307. package/lib/rules/one-var-declaration-per-line.js +117 -0
  308. package/lib/rules/one-var.js +717 -0
  309. package/lib/rules/operator-assignment.js +270 -0
  310. package/lib/rules/operator-linebreak.js +315 -0
  311. package/lib/rules/padded-blocks.js +366 -0
  312. package/lib/rules/padding-line-between-statements.js +612 -0
  313. package/lib/rules/prefer-arrow-callback.js +437 -0
  314. package/lib/rules/prefer-const.js +546 -0
  315. package/lib/rules/prefer-destructuring.js +332 -0
  316. package/lib/rules/prefer-exponentiation-operator.js +235 -0
  317. package/lib/rules/prefer-named-capture-group.js +197 -0
  318. package/lib/rules/prefer-numeric-literals.js +157 -0
  319. package/lib/rules/prefer-object-has-own.js +148 -0
  320. package/lib/rules/prefer-object-spread.js +319 -0
  321. package/lib/rules/prefer-promise-reject-errors.js +154 -0
  322. package/lib/rules/prefer-reflect.js +150 -0
  323. package/lib/rules/prefer-regex-literals.js +605 -0
  324. package/lib/rules/prefer-rest-params.js +117 -0
  325. package/lib/rules/prefer-spread.js +91 -0
  326. package/lib/rules/prefer-template.js +347 -0
  327. package/lib/rules/preserve-caught-error.js +535 -0
  328. package/lib/rules/quote-props.js +394 -0
  329. package/lib/rules/quotes.js +416 -0
  330. package/lib/rules/radix.js +193 -0
  331. package/lib/rules/require-atomic-updates.js +365 -0
  332. package/lib/rules/require-await.js +184 -0
  333. package/lib/rules/require-unicode-regexp.js +317 -0
  334. package/lib/rules/require-yield.js +86 -0
  335. package/lib/rules/rest-spread-spacing.js +150 -0
  336. package/lib/rules/semi-spacing.js +297 -0
  337. package/lib/rules/semi-style.js +218 -0
  338. package/lib/rules/semi.js +476 -0
  339. package/lib/rules/sort-imports.js +319 -0
  340. package/lib/rules/sort-keys.js +268 -0
  341. package/lib/rules/sort-vars.js +140 -0
  342. package/lib/rules/space-before-blocks.js +232 -0
  343. package/lib/rules/space-before-function-paren.js +202 -0
  344. package/lib/rules/space-in-parens.js +374 -0
  345. package/lib/rules/space-infix-ops.js +249 -0
  346. package/lib/rules/space-unary-ops.js +400 -0
  347. package/lib/rules/spaced-comment.js +447 -0
  348. package/lib/rules/strict.js +314 -0
  349. package/lib/rules/switch-colon-spacing.js +158 -0
  350. package/lib/rules/symbol-description.js +70 -0
  351. package/lib/rules/template-curly-spacing.js +168 -0
  352. package/lib/rules/template-tag-spacing.js +121 -0
  353. package/lib/rules/unicode-bom.js +73 -0
  354. package/lib/rules/use-isnan.js +268 -0
  355. package/lib/rules/utils/ast-utils.js +2828 -0
  356. package/lib/rules/utils/char-source.js +247 -0
  357. package/lib/rules/utils/fix-tracker.js +125 -0
  358. package/lib/rules/utils/keywords.js +67 -0
  359. package/lib/rules/utils/lazy-loading-rule-map.js +118 -0
  360. package/lib/rules/utils/regular-expressions.js +58 -0
  361. package/lib/rules/utils/unicode/index.js +16 -0
  362. package/lib/rules/utils/unicode/is-combining-character.js +13 -0
  363. package/lib/rules/utils/unicode/is-emoji-modifier.js +13 -0
  364. package/lib/rules/utils/unicode/is-regional-indicator-symbol.js +13 -0
  365. package/lib/rules/utils/unicode/is-surrogate-pair.js +14 -0
  366. package/lib/rules/valid-typeof.js +171 -0
  367. package/lib/rules/vars-on-top.js +165 -0
  368. package/lib/rules/wrap-iife.js +238 -0
  369. package/lib/rules/wrap-regex.js +91 -0
  370. package/lib/rules/yield-star-spacing.js +158 -0
  371. package/lib/rules/yoda.js +362 -0
  372. package/lib/services/parser-service.js +64 -0
  373. package/lib/services/processor-service.js +100 -0
  374. package/lib/services/suppressions-service.js +302 -0
  375. package/lib/services/warning-service.js +87 -0
  376. package/lib/shared/ajv.js +34 -0
  377. package/lib/shared/assert.js +21 -0
  378. package/lib/shared/ast-utils.js +30 -0
  379. package/lib/shared/deep-merge-arrays.js +62 -0
  380. package/lib/shared/directives.js +16 -0
  381. package/lib/shared/flags.js +89 -0
  382. package/lib/shared/logging.js +38 -0
  383. package/lib/shared/naming.js +109 -0
  384. package/lib/shared/option-utils.js +63 -0
  385. package/lib/shared/relative-module-resolver.js +28 -0
  386. package/lib/shared/runtime-info.js +177 -0
  387. package/lib/shared/serialization.js +78 -0
  388. package/lib/shared/severity.js +49 -0
  389. package/lib/shared/stats.js +30 -0
  390. package/lib/shared/string-utils.js +58 -0
  391. package/lib/shared/text-table.js +68 -0
  392. package/lib/shared/translate-cli-options.js +223 -0
  393. package/lib/shared/traverser.js +202 -0
  394. package/lib/types/config-api.d.ts +12 -0
  395. package/lib/types/index.d.ts +1482 -0
  396. package/lib/types/rules.d.ts +5603 -0
  397. package/lib/types/universal.d.ts +6 -0
  398. package/lib/types/use-at-your-own-risk.d.ts +34 -0
  399. package/lib/universal.js +10 -0
  400. package/lib/unsupported-api.js +26 -0
  401. package/messages/all-files-ignored.js +16 -0
  402. package/messages/all-matched-files-ignored.js +21 -0
  403. package/messages/config-file-missing.js +16 -0
  404. package/messages/config-plugin-missing.js +14 -0
  405. package/messages/config-serialize-function.js +30 -0
  406. package/messages/eslintrc-incompat.js +117 -0
  407. package/messages/eslintrc-plugins.js +27 -0
  408. package/messages/extend-config-missing.js +13 -0
  409. package/messages/failed-to-read-json.js +11 -0
  410. package/messages/file-not-found.js +10 -0
  411. package/messages/invalid-rule-options.js +17 -0
  412. package/messages/invalid-rule-severity.js +13 -0
  413. package/messages/no-config-found.js +15 -0
  414. package/messages/plugin-conflict.js +22 -0
  415. package/messages/plugin-invalid.js +16 -0
  416. package/messages/plugin-missing.js +19 -0
  417. package/messages/print-config-with-directory-path.js +8 -0
  418. package/messages/shared.js +23 -0
  419. package/messages/whitespace-found.js +11 -0
  420. package/package.json +220 -0
@@ -0,0 +1,2828 @@
1
+ /**
2
+ * @fileoverview Common utils for AST.
3
+ * @author Gyandeep Singh
4
+ */
5
+
6
+ "use strict";
7
+
8
+ //------------------------------------------------------------------------------
9
+ // Requirements
10
+ //------------------------------------------------------------------------------
11
+
12
+ const { KEYS: eslintVisitorKeys } = require("eslint-visitor-keys");
13
+ const esutils = require("esutils");
14
+ const espree = require("espree");
15
+ const escapeRegExp = require("escape-string-regexp");
16
+ const {
17
+ breakableTypePattern,
18
+ createGlobalLinebreakMatcher,
19
+ lineBreakPattern,
20
+ shebangPattern,
21
+ } = require("../../shared/ast-utils");
22
+ const globals = require("../../../conf/globals");
23
+ const { LATEST_ECMA_VERSION } = require("../../../conf/ecma-version");
24
+
25
+ //------------------------------------------------------------------------------
26
+ // Helpers
27
+ //------------------------------------------------------------------------------
28
+
29
+ const anyFunctionPattern =
30
+ /^(?:Function(?:Declaration|Expression)|ArrowFunctionExpression)$/u;
31
+ const anyLoopPattern = /^(?:DoWhile|For|ForIn|ForOf|While)Statement$/u;
32
+ const arrayMethodWithThisArgPattern =
33
+ /^(?:every|filter|find(?:Last)?(?:Index)?|flatMap|forEach|map|some)$/u;
34
+ const arrayOrTypedArrayPattern = /Array$/u;
35
+ const bindOrCallOrApplyPattern = /^(?:bind|call|apply)$/u;
36
+ const thisTagPattern = /^[\s*]*@this/mu;
37
+
38
+ const COMMENTS_IGNORE_PATTERN =
39
+ /^\s*(?:eslint|jshint\s+|jslint\s+|istanbul\s+|globals?\s+|exported\s+|jscs)/u;
40
+ const ESLINT_DIRECTIVE_PATTERN = /^(?:eslint[- ]|(?:globals?|exported) )/u;
41
+ const LINEBREAKS = new Set(["\r\n", "\r", "\n", "\u2028", "\u2029"]);
42
+
43
+ // A set of node types that can contain a list of statements
44
+ const STATEMENT_LIST_PARENTS = new Set([
45
+ "Program",
46
+ "BlockStatement",
47
+ "StaticBlock",
48
+ "SwitchCase",
49
+ ]);
50
+ const LEXICAL_DECLARATION_KINDS = new Set([
51
+ "let",
52
+ "const",
53
+ "using",
54
+ "await using",
55
+ ]);
56
+
57
+ const DECIMAL_INTEGER_PATTERN = /^(?:0|0[0-7]*[89]\d*|[1-9](?:_?\d)*)$/u;
58
+
59
+ // Tests the presence of at least one LegacyOctalEscapeSequence or NonOctalDecimalEscapeSequence in a raw string
60
+ const OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN =
61
+ /^(?:[^\\]|\\.)*\\(?:[1-9]|0\d)/su;
62
+
63
+ const LOGICAL_ASSIGNMENT_OPERATORS = new Set(["&&=", "||=", "??="]);
64
+
65
+ /**
66
+ * All builtin global variables defined in the latest ECMAScript specification.
67
+ * @type {Record<string,boolean>} Key is the name of the variable. Value is `true` if the variable is considered writable, `false` otherwise.
68
+ */
69
+ const ECMASCRIPT_GLOBALS = globals[`es${LATEST_ECMA_VERSION}`];
70
+
71
+ /**
72
+ * Checks reference if is non initializer and writable.
73
+ * @param {Reference} reference A reference to check.
74
+ * @param {number} index The index of the reference in the references.
75
+ * @param {Reference[]} references The array that the reference belongs to.
76
+ * @returns {boolean} Success/Failure
77
+ * @private
78
+ */
79
+ function isModifyingReference(reference, index, references) {
80
+ const identifier = reference.identifier;
81
+
82
+ /*
83
+ * Destructuring assignments can have multiple default value, so
84
+ * possibly there are multiple writeable references for the same
85
+ * identifier.
86
+ */
87
+ const modifyingDifferentIdentifier =
88
+ index === 0 || references[index - 1].identifier !== identifier;
89
+
90
+ return (
91
+ identifier &&
92
+ reference.init === false &&
93
+ reference.isWrite() &&
94
+ modifyingDifferentIdentifier
95
+ );
96
+ }
97
+
98
+ /**
99
+ * Checks whether the given string starts with uppercase or not.
100
+ * @param {string} s The string to check.
101
+ * @returns {boolean} `true` if the string starts with uppercase.
102
+ */
103
+ function startsWithUpperCase(s) {
104
+ return s[0] !== s[0].toLocaleLowerCase();
105
+ }
106
+
107
+ /**
108
+ * Checks whether or not a node is a constructor.
109
+ * @param {ASTNode} node A function node to check.
110
+ * @returns {boolean} Whether or not a node is a constructor.
111
+ */
112
+ function isES5Constructor(node) {
113
+ return node.id && startsWithUpperCase(node.id.name);
114
+ }
115
+
116
+ /**
117
+ * Finds a function node from ancestors of a node.
118
+ * @param {ASTNode} node A start node to find.
119
+ * @returns {Node|null} A found function node.
120
+ */
121
+ function getUpperFunction(node) {
122
+ for (
123
+ let currentNode = node;
124
+ currentNode;
125
+ currentNode = currentNode.parent
126
+ ) {
127
+ if (anyFunctionPattern.test(currentNode.type)) {
128
+ return currentNode;
129
+ }
130
+ }
131
+ return null;
132
+ }
133
+
134
+ /**
135
+ * Checks whether a given node is a function node or not.
136
+ * The following types are function nodes:
137
+ *
138
+ * - ArrowFunctionExpression
139
+ * - FunctionDeclaration
140
+ * - FunctionExpression
141
+ * @param {ASTNode|null} node A node to check.
142
+ * @returns {boolean} `true` if the node is a function node.
143
+ */
144
+ function isFunction(node) {
145
+ return Boolean(node && anyFunctionPattern.test(node.type));
146
+ }
147
+
148
+ /**
149
+ * Checks whether a given node is a loop node or not.
150
+ * The following types are loop nodes:
151
+ *
152
+ * - DoWhileStatement
153
+ * - ForInStatement
154
+ * - ForOfStatement
155
+ * - ForStatement
156
+ * - WhileStatement
157
+ * @param {ASTNode|null} node A node to check.
158
+ * @returns {boolean} `true` if the node is a loop node.
159
+ */
160
+ function isLoop(node) {
161
+ return Boolean(node && anyLoopPattern.test(node.type));
162
+ }
163
+
164
+ /**
165
+ * Checks whether the given node is in a loop or not.
166
+ * @param {ASTNode} node The node to check.
167
+ * @returns {boolean} `true` if the node is in a loop.
168
+ */
169
+ function isInLoop(node) {
170
+ for (
171
+ let currentNode = node;
172
+ currentNode && !isFunction(currentNode);
173
+ currentNode = currentNode.parent
174
+ ) {
175
+ if (isLoop(currentNode)) {
176
+ return true;
177
+ }
178
+ }
179
+
180
+ return false;
181
+ }
182
+
183
+ /**
184
+ * Determines whether the given node is a `null` literal.
185
+ * @param {ASTNode} node The node to check
186
+ * @returns {boolean} `true` if the node is a `null` literal
187
+ */
188
+ function isNullLiteral(node) {
189
+ /*
190
+ * Checking `node.value === null` does not guarantee that a literal is a null literal.
191
+ * When parsing values that cannot be represented in the current environment (e.g. unicode
192
+ * regexes in Node 4), `node.value` is set to `null` because it wouldn't be possible to
193
+ * set `node.value` to a unicode regex. To make sure a literal is actually `null`, check
194
+ * `node.regex` instead. Also see: https://github.com/eslint/eslint/issues/8020
195
+ */
196
+ return (
197
+ node.type === "Literal" &&
198
+ node.value === null &&
199
+ !node.regex &&
200
+ !node.bigint
201
+ );
202
+ }
203
+
204
+ /**
205
+ * Checks whether or not a node is `null` or `undefined`.
206
+ * @param {ASTNode} node A node to check.
207
+ * @returns {boolean} Whether or not the node is a `null` or `undefined`.
208
+ * @public
209
+ */
210
+ function isNullOrUndefined(node) {
211
+ return (
212
+ isNullLiteral(node) ||
213
+ (node.type === "Identifier" && node.name === "undefined") ||
214
+ (node.type === "UnaryExpression" && node.operator === "void")
215
+ );
216
+ }
217
+
218
+ /**
219
+ * Checks whether or not a node is callee.
220
+ * @param {ASTNode} node A node to check.
221
+ * @returns {boolean} Whether or not the node is callee.
222
+ */
223
+ function isCallee(node) {
224
+ return node.parent.type === "CallExpression" && node.parent.callee === node;
225
+ }
226
+
227
+ /**
228
+ * Returns the result of the string conversion applied to the evaluated value of the given expression node,
229
+ * if it can be determined statically.
230
+ *
231
+ * This function returns a `string` value for all `Literal` nodes and simple `TemplateLiteral` nodes only.
232
+ * In all other cases, this function returns `null`.
233
+ * @param {ASTNode} node Expression node.
234
+ * @returns {string|null} String value if it can be determined. Otherwise, `null`.
235
+ */
236
+ function getStaticStringValue(node) {
237
+ switch (node.type) {
238
+ case "Literal":
239
+ if (node.value === null) {
240
+ if (isNullLiteral(node)) {
241
+ return String(node.value); // "null"
242
+ }
243
+ if (node.regex) {
244
+ return `/${node.regex.pattern}/${node.regex.flags}`;
245
+ }
246
+ if (node.bigint) {
247
+ return node.bigint;
248
+ }
249
+
250
+ // Otherwise, this is an unknown literal. The function will return null.
251
+ } else {
252
+ return String(node.value);
253
+ }
254
+ break;
255
+ case "TemplateLiteral":
256
+ if (node.expressions.length === 0 && node.quasis.length === 1) {
257
+ return node.quasis[0].value.cooked;
258
+ }
259
+ break;
260
+
261
+ // no default
262
+ }
263
+
264
+ return null;
265
+ }
266
+
267
+ /**
268
+ * Gets the property name of a given node.
269
+ * The node can be a MemberExpression, a Property, or a MethodDefinition.
270
+ *
271
+ * If the name is dynamic, this returns `null`.
272
+ *
273
+ * For examples:
274
+ *
275
+ * a.b // => "b"
276
+ * a["b"] // => "b"
277
+ * a['b'] // => "b"
278
+ * a[`b`] // => "b"
279
+ * a[100] // => "100"
280
+ * a[b] // => null
281
+ * a["a" + "b"] // => null
282
+ * a[tag`b`] // => null
283
+ * a[`${b}`] // => null
284
+ *
285
+ * let a = {b: 1} // => "b"
286
+ * let a = {["b"]: 1} // => "b"
287
+ * let a = {['b']: 1} // => "b"
288
+ * let a = {[`b`]: 1} // => "b"
289
+ * let a = {[100]: 1} // => "100"
290
+ * let a = {[b]: 1} // => null
291
+ * let a = {["a" + "b"]: 1} // => null
292
+ * let a = {[tag`b`]: 1} // => null
293
+ * let a = {[`${b}`]: 1} // => null
294
+ * @param {ASTNode} node The node to get.
295
+ * @returns {string|null} The property name if static. Otherwise, null.
296
+ */
297
+ function getStaticPropertyName(node) {
298
+ let prop;
299
+
300
+ switch (node && node.type) {
301
+ case "ChainExpression":
302
+ return getStaticPropertyName(node.expression);
303
+
304
+ case "Property":
305
+ case "PropertyDefinition":
306
+ case "MethodDefinition":
307
+ case "TSPropertySignature":
308
+ case "TSMethodSignature":
309
+ prop = node.key;
310
+ break;
311
+
312
+ case "MemberExpression":
313
+ prop = node.property;
314
+ break;
315
+
316
+ // no default
317
+ }
318
+
319
+ if (prop) {
320
+ if (prop.type === "Identifier" && !node.computed) {
321
+ return prop.name;
322
+ }
323
+
324
+ return getStaticStringValue(prop);
325
+ }
326
+
327
+ return null;
328
+ }
329
+
330
+ /**
331
+ * Retrieve `ChainExpression#expression` value if the given node a `ChainExpression` node. Otherwise, pass through it.
332
+ * @param {ASTNode} node The node to address.
333
+ * @returns {ASTNode} The `ChainExpression#expression` value if the node is a `ChainExpression` node. Otherwise, the node.
334
+ */
335
+ function skipChainExpression(node) {
336
+ return node && node.type === "ChainExpression" ? node.expression : node;
337
+ }
338
+
339
+ /**
340
+ * Check if the `actual` is an expected value.
341
+ * @param {string} actual The string value to check.
342
+ * @param {string | RegExp} expected The expected string value or pattern.
343
+ * @returns {boolean} `true` if the `actual` is an expected value.
344
+ */
345
+ function checkText(actual, expected) {
346
+ return typeof expected === "string"
347
+ ? actual === expected
348
+ : expected.test(actual);
349
+ }
350
+
351
+ /**
352
+ * Check if a given node is an Identifier node with a given name.
353
+ * @param {ASTNode} node The node to check.
354
+ * @param {string | RegExp} name The expected name or the expected pattern of the object name.
355
+ * @returns {boolean} `true` if the node is an Identifier node with the name.
356
+ */
357
+ function isSpecificId(node, name) {
358
+ return node.type === "Identifier" && checkText(node.name, name);
359
+ }
360
+
361
+ /**
362
+ * Check if a given node is member access with a given object name and property name pair.
363
+ * This is regardless of optional or not.
364
+ * @param {ASTNode} node The node to check.
365
+ * @param {string | RegExp | null} objectName The expected name or the expected pattern of the object name. If this is nullish, this method doesn't check object.
366
+ * @param {string | RegExp | null} propertyName The expected name or the expected pattern of the property name. If this is nullish, this method doesn't check property.
367
+ * @returns {boolean} `true` if the node is member access with the object name and property name pair.
368
+ * The node is a `MemberExpression` or `ChainExpression`.
369
+ */
370
+ function isSpecificMemberAccess(node, objectName, propertyName) {
371
+ const checkNode = skipChainExpression(node);
372
+
373
+ if (checkNode.type !== "MemberExpression") {
374
+ return false;
375
+ }
376
+
377
+ if (objectName && !isSpecificId(checkNode.object, objectName)) {
378
+ return false;
379
+ }
380
+
381
+ if (propertyName) {
382
+ const actualPropertyName = getStaticPropertyName(checkNode);
383
+
384
+ if (
385
+ typeof actualPropertyName !== "string" ||
386
+ !checkText(actualPropertyName, propertyName)
387
+ ) {
388
+ return false;
389
+ }
390
+ }
391
+
392
+ return true;
393
+ }
394
+
395
+ /**
396
+ * Check if two literal nodes are the same value.
397
+ * @param {ASTNode} left The Literal node to compare.
398
+ * @param {ASTNode} right The other Literal node to compare.
399
+ * @returns {boolean} `true` if the two literal nodes are the same value.
400
+ */
401
+ function equalLiteralValue(left, right) {
402
+ // RegExp literal.
403
+ if (left.regex || right.regex) {
404
+ return Boolean(
405
+ left.regex &&
406
+ right.regex &&
407
+ left.regex.pattern === right.regex.pattern &&
408
+ left.regex.flags === right.regex.flags,
409
+ );
410
+ }
411
+
412
+ // BigInt literal.
413
+ if (left.bigint || right.bigint) {
414
+ return left.bigint === right.bigint;
415
+ }
416
+
417
+ return left.value === right.value;
418
+ }
419
+
420
+ /**
421
+ * Check if two expressions reference the same value. For example:
422
+ * a = a
423
+ * a.b = a.b
424
+ * a[0] = a[0]
425
+ * a['b'] = a['b']
426
+ * @param {ASTNode} left The left side of the comparison.
427
+ * @param {ASTNode} right The right side of the comparison.
428
+ * @param {boolean} [disableStaticComputedKey] Don't address `a.b` and `a["b"]` are the same if `true`. For backward compatibility.
429
+ * @returns {boolean} `true` if both sides match and reference the same value.
430
+ */
431
+ function isSameReference(left, right, disableStaticComputedKey = false) {
432
+ if (left.type !== right.type) {
433
+ // Handle `a.b` and `a?.b` are samely.
434
+ if (left.type === "ChainExpression") {
435
+ return isSameReference(
436
+ left.expression,
437
+ right,
438
+ disableStaticComputedKey,
439
+ );
440
+ }
441
+ if (right.type === "ChainExpression") {
442
+ return isSameReference(
443
+ left,
444
+ right.expression,
445
+ disableStaticComputedKey,
446
+ );
447
+ }
448
+
449
+ return false;
450
+ }
451
+
452
+ switch (left.type) {
453
+ case "Super":
454
+ case "ThisExpression":
455
+ return true;
456
+
457
+ case "Identifier":
458
+ case "PrivateIdentifier":
459
+ return left.name === right.name;
460
+ case "Literal":
461
+ return equalLiteralValue(left, right);
462
+
463
+ case "ChainExpression":
464
+ return isSameReference(
465
+ left.expression,
466
+ right.expression,
467
+ disableStaticComputedKey,
468
+ );
469
+
470
+ case "MemberExpression": {
471
+ if (!disableStaticComputedKey) {
472
+ const nameA = getStaticPropertyName(left);
473
+
474
+ // x.y = x["y"]
475
+ if (nameA !== null) {
476
+ return (
477
+ isSameReference(
478
+ left.object,
479
+ right.object,
480
+ disableStaticComputedKey,
481
+ ) && nameA === getStaticPropertyName(right)
482
+ );
483
+ }
484
+ }
485
+
486
+ /*
487
+ * x[0] = x[0]
488
+ * x[y] = x[y]
489
+ * x.y = x.y
490
+ */
491
+ return (
492
+ left.computed === right.computed &&
493
+ isSameReference(
494
+ left.object,
495
+ right.object,
496
+ disableStaticComputedKey,
497
+ ) &&
498
+ isSameReference(
499
+ left.property,
500
+ right.property,
501
+ disableStaticComputedKey,
502
+ )
503
+ );
504
+ }
505
+
506
+ default:
507
+ return false;
508
+ }
509
+ }
510
+
511
+ /**
512
+ * Checks whether or not a node is `Reflect.apply`.
513
+ * @param {ASTNode} node A node to check.
514
+ * @returns {boolean} Whether or not the node is a `Reflect.apply`.
515
+ */
516
+ function isReflectApply(node) {
517
+ return isSpecificMemberAccess(node, "Reflect", "apply");
518
+ }
519
+
520
+ /**
521
+ * Checks whether or not a node is `Array.from`.
522
+ * @param {ASTNode} node A node to check.
523
+ * @returns {boolean} Whether or not the node is a `Array.from`.
524
+ */
525
+ function isArrayFromMethod(node) {
526
+ return isSpecificMemberAccess(node, arrayOrTypedArrayPattern, "from");
527
+ }
528
+
529
+ /**
530
+ * Checks whether or not a node is a method which expects a function as a first argument, and `thisArg` as a second argument.
531
+ * @param {ASTNode} node A node to check.
532
+ * @returns {boolean} Whether or not the node is a method which expects a function as a first argument, and `thisArg` as a second argument.
533
+ */
534
+ function isMethodWhichHasThisArg(node) {
535
+ return isSpecificMemberAccess(node, null, arrayMethodWithThisArgPattern);
536
+ }
537
+
538
+ /**
539
+ * Creates the negate function of the given function.
540
+ * @param {Function} f The function to negate.
541
+ * @returns {Function} Negated function.
542
+ */
543
+ function negate(f) {
544
+ return token => !f(token);
545
+ }
546
+
547
+ /**
548
+ * Determines if a node is surrounded by parentheses.
549
+ * @param {SourceCode} sourceCode The ESLint source code object
550
+ * @param {ASTNode} node The node to be checked.
551
+ * @returns {boolean} True if the node is parenthesised.
552
+ * @private
553
+ */
554
+ function isParenthesised(sourceCode, node) {
555
+ const previousToken = sourceCode.getTokenBefore(node),
556
+ nextToken = sourceCode.getTokenAfter(node);
557
+
558
+ return (
559
+ Boolean(previousToken && nextToken) &&
560
+ previousToken.value === "(" &&
561
+ previousToken.range[1] <= node.range[0] &&
562
+ nextToken.value === ")" &&
563
+ nextToken.range[0] >= node.range[1]
564
+ );
565
+ }
566
+
567
+ /**
568
+ * Checks if the given token is a `=` token or not.
569
+ * @param {Token} token The token to check.
570
+ * @returns {boolean} `true` if the token is a `=` token.
571
+ */
572
+ function isEqToken(token) {
573
+ return token.value === "=" && token.type === "Punctuator";
574
+ }
575
+
576
+ /**
577
+ * Checks if the given token is an arrow token or not.
578
+ * @param {Token} token The token to check.
579
+ * @returns {boolean} `true` if the token is an arrow token.
580
+ */
581
+ function isArrowToken(token) {
582
+ return token.value === "=>" && token.type === "Punctuator";
583
+ }
584
+
585
+ /**
586
+ * Checks if the given token is a comma token or not.
587
+ * @param {Token} token The token to check.
588
+ * @returns {boolean} `true` if the token is a comma token.
589
+ */
590
+ function isCommaToken(token) {
591
+ return token.value === "," && token.type === "Punctuator";
592
+ }
593
+
594
+ /**
595
+ * Checks if the given token is a dot token or not.
596
+ * @param {Token} token The token to check.
597
+ * @returns {boolean} `true` if the token is a dot token.
598
+ */
599
+ function isDotToken(token) {
600
+ return token.value === "." && token.type === "Punctuator";
601
+ }
602
+
603
+ /**
604
+ * Checks if the given token is a `?.` token or not.
605
+ * @param {Token} token The token to check.
606
+ * @returns {boolean} `true` if the token is a `?.` token.
607
+ */
608
+ function isQuestionDotToken(token) {
609
+ return token.value === "?." && token.type === "Punctuator";
610
+ }
611
+
612
+ /**
613
+ * Checks if the given token is a semicolon token or not.
614
+ * @param {Token} token The token to check.
615
+ * @returns {boolean} `true` if the token is a semicolon token.
616
+ */
617
+ function isSemicolonToken(token) {
618
+ return token.value === ";" && token.type === "Punctuator";
619
+ }
620
+
621
+ /**
622
+ * Checks if the given token is a colon token or not.
623
+ * @param {Token} token The token to check.
624
+ * @returns {boolean} `true` if the token is a colon token.
625
+ */
626
+ function isColonToken(token) {
627
+ return token.value === ":" && token.type === "Punctuator";
628
+ }
629
+
630
+ /**
631
+ * Checks if the given token is an opening parenthesis token or not.
632
+ * @param {Token} token The token to check.
633
+ * @returns {boolean} `true` if the token is an opening parenthesis token.
634
+ */
635
+ function isOpeningParenToken(token) {
636
+ return token.value === "(" && token.type === "Punctuator";
637
+ }
638
+
639
+ /**
640
+ * Checks if the given token is a closing parenthesis token or not.
641
+ * @param {Token} token The token to check.
642
+ * @returns {boolean} `true` if the token is a closing parenthesis token.
643
+ */
644
+ function isClosingParenToken(token) {
645
+ return token.value === ")" && token.type === "Punctuator";
646
+ }
647
+
648
+ /**
649
+ * Checks if the given token is an opening square bracket token or not.
650
+ * @param {Token} token The token to check.
651
+ * @returns {boolean} `true` if the token is an opening square bracket token.
652
+ */
653
+ function isOpeningBracketToken(token) {
654
+ return token.value === "[" && token.type === "Punctuator";
655
+ }
656
+
657
+ /**
658
+ * Checks if the given token is a closing square bracket token or not.
659
+ * @param {Token} token The token to check.
660
+ * @returns {boolean} `true` if the token is a closing square bracket token.
661
+ */
662
+ function isClosingBracketToken(token) {
663
+ return token.value === "]" && token.type === "Punctuator";
664
+ }
665
+
666
+ /**
667
+ * Checks if the given token is an opening brace token or not.
668
+ * @param {Token} token The token to check.
669
+ * @returns {boolean} `true` if the token is an opening brace token.
670
+ */
671
+ function isOpeningBraceToken(token) {
672
+ return token.value === "{" && token.type === "Punctuator";
673
+ }
674
+
675
+ /**
676
+ * Checks if the given token is a closing brace token or not.
677
+ * @param {Token} token The token to check.
678
+ * @returns {boolean} `true` if the token is a closing brace token.
679
+ */
680
+ function isClosingBraceToken(token) {
681
+ return token.value === "}" && token.type === "Punctuator";
682
+ }
683
+
684
+ /**
685
+ * Checks if the given token is a comment token or not.
686
+ * @param {Token} token The token to check.
687
+ * @returns {boolean} `true` if the token is a comment token.
688
+ */
689
+ function isCommentToken(token) {
690
+ return (
691
+ token.type === "Line" ||
692
+ token.type === "Block" ||
693
+ token.type === "Shebang"
694
+ );
695
+ }
696
+
697
+ /**
698
+ * Checks if the given token is a keyword token or not.
699
+ * @param {Token} token The token to check.
700
+ * @returns {boolean} `true` if the token is a keyword token.
701
+ */
702
+ function isKeywordToken(token) {
703
+ return token.type === "Keyword";
704
+ }
705
+
706
+ /**
707
+ * Checks whether the given node represents an ES6 export declaration.
708
+ * @param {ASTNode} node A node to check.
709
+ * @returns {boolean} `true` if the node is an export declaration.
710
+ * @private
711
+ */
712
+ function isExportDeclaration(node) {
713
+ return (
714
+ node.type === "ExportDefaultDeclaration" ||
715
+ node.type === "ExportNamedDeclaration" ||
716
+ node.type === "ExportAllDeclaration"
717
+ );
718
+ }
719
+
720
+ /**
721
+ * Checks for the presence of a JSDoc comment for the given node and returns it.
722
+ * @param {ASTNode} node The node to get the comment for.
723
+ * @param {SourceCode} sourceCode A SourceCode instance to get comments.
724
+ * @returns {Token|null} The Block comment token containing the JSDoc comment for the given node or null if not found.
725
+ * @private
726
+ */
727
+ function findJSDocComment(node, sourceCode) {
728
+ const tokenBefore = sourceCode.getTokenBefore(node, {
729
+ includeComments: true,
730
+ });
731
+
732
+ if (
733
+ tokenBefore &&
734
+ tokenBefore.type === "Block" &&
735
+ tokenBefore.value.charAt(0) === "*" &&
736
+ node.loc.start.line - tokenBefore.loc.end.line <= 1
737
+ ) {
738
+ return tokenBefore;
739
+ }
740
+
741
+ return null;
742
+ }
743
+
744
+ /**
745
+ * Retrieves the JSDoc comment for a given node.
746
+ * @param {ASTNode} node The node to get the comment for.
747
+ * @param {SourceCode} sourceCode A SourceCode instance to get comments.
748
+ * @returns {Token|null} The Block comment token containing the JSDoc comment for the given node or null if not found.
749
+ * @private
750
+ */
751
+ function getJSDocComment(node, sourceCode) {
752
+ let parent = node.parent;
753
+
754
+ switch (node.type) {
755
+ case "ClassDeclaration":
756
+ case "FunctionDeclaration":
757
+ return findJSDocComment(
758
+ isExportDeclaration(parent) ? parent : node,
759
+ sourceCode,
760
+ );
761
+
762
+ case "ClassExpression":
763
+ return findJSDocComment(parent.parent, sourceCode);
764
+
765
+ case "ArrowFunctionExpression":
766
+ case "FunctionExpression":
767
+ if (
768
+ parent.type !== "CallExpression" &&
769
+ parent.type !== "NewExpression"
770
+ ) {
771
+ while (
772
+ !sourceCode.getCommentsBefore(parent).length &&
773
+ !/Function/u.test(parent.type) &&
774
+ parent.type !== "MethodDefinition" &&
775
+ parent.type !== "Property"
776
+ ) {
777
+ parent = parent.parent;
778
+
779
+ if (!parent) {
780
+ break;
781
+ }
782
+ }
783
+
784
+ if (
785
+ parent &&
786
+ parent.type !== "FunctionDeclaration" &&
787
+ parent.type !== "Program"
788
+ ) {
789
+ return findJSDocComment(parent, sourceCode);
790
+ }
791
+ }
792
+
793
+ return findJSDocComment(node, sourceCode);
794
+
795
+ // falls through
796
+ default:
797
+ return null;
798
+ }
799
+ }
800
+
801
+ /**
802
+ * Checks whether or not a node has a `@this` tag in its comments.
803
+ * @param {ASTNode} node A node to check.
804
+ * @param {SourceCode} sourceCode A SourceCode instance to get comments.
805
+ * @returns {boolean} Whether or not the node has a `@this` tag in its comments.
806
+ */
807
+ function hasJSDocThisTag(node, sourceCode) {
808
+ const jsdocComment = getJSDocComment(node, sourceCode);
809
+
810
+ if (jsdocComment && thisTagPattern.test(jsdocComment.value)) {
811
+ return true;
812
+ }
813
+
814
+ // Checks `@this` in its leading comments for callbacks,
815
+ // because callbacks don't have its JSDoc comment.
816
+ // e.g.
817
+ // sinon.test(/* @this sinon.Sandbox */function() { this.spy(); });
818
+ return sourceCode
819
+ .getCommentsBefore(node)
820
+ .some(comment => thisTagPattern.test(comment.value));
821
+ }
822
+
823
+ /**
824
+ * Gets the `(` token of the given function node.
825
+ * @param {ASTNode} node The function node to get.
826
+ * @param {SourceCode} sourceCode The source code object to get tokens.
827
+ * @returns {Token} `(` token.
828
+ */
829
+ function getOpeningParenOfParams(node, sourceCode) {
830
+ // If the node is an arrow function and doesn't have parens, this returns the identifier of the first param.
831
+ if (node.type === "ArrowFunctionExpression" && node.params.length === 1) {
832
+ const argToken = sourceCode.getFirstToken(node.params[0]);
833
+ const maybeParenToken = sourceCode.getTokenBefore(argToken);
834
+
835
+ return isOpeningParenToken(maybeParenToken)
836
+ ? maybeParenToken
837
+ : argToken;
838
+ }
839
+
840
+ // Otherwise, returns paren.
841
+ return node.id
842
+ ? sourceCode.getTokenAfter(node.id, isOpeningParenToken)
843
+ : sourceCode.getFirstToken(node, isOpeningParenToken);
844
+ }
845
+
846
+ /**
847
+ * Checks whether or not the tokens of two given nodes are same.
848
+ * @param {ASTNode} left A node 1 to compare.
849
+ * @param {ASTNode} right A node 2 to compare.
850
+ * @param {SourceCode} sourceCode The ESLint source code object.
851
+ * @returns {boolean} the source code for the given node.
852
+ */
853
+ function equalTokens(left, right, sourceCode) {
854
+ const tokensL = sourceCode.getTokens(left);
855
+ const tokensR = sourceCode.getTokens(right);
856
+
857
+ if (tokensL.length !== tokensR.length) {
858
+ return false;
859
+ }
860
+ for (let i = 0; i < tokensL.length; ++i) {
861
+ if (
862
+ tokensL[i].type !== tokensR[i].type ||
863
+ tokensL[i].value !== tokensR[i].value
864
+ ) {
865
+ return false;
866
+ }
867
+ }
868
+
869
+ return true;
870
+ }
871
+
872
+ /**
873
+ * Check if the given node is a true logical expression or not.
874
+ *
875
+ * The three binary expressions logical-or (`||`), logical-and (`&&`), and
876
+ * coalesce (`??`) are known as `ShortCircuitExpression`.
877
+ * But ESTree represents those by `LogicalExpression` node.
878
+ *
879
+ * This function rejects coalesce expressions of `LogicalExpression` node.
880
+ * @param {ASTNode} node The node to check.
881
+ * @returns {boolean} `true` if the node is `&&` or `||`.
882
+ * @see https://tc39.es/ecma262/#prod-ShortCircuitExpression
883
+ */
884
+ function isLogicalExpression(node) {
885
+ return (
886
+ node.type === "LogicalExpression" &&
887
+ (node.operator === "&&" || node.operator === "||")
888
+ );
889
+ }
890
+
891
+ /**
892
+ * Check if the given node is a nullish coalescing expression or not.
893
+ *
894
+ * The three binary expressions logical-or (`||`), logical-and (`&&`), and
895
+ * coalesce (`??`) are known as `ShortCircuitExpression`.
896
+ * But ESTree represents those by `LogicalExpression` node.
897
+ *
898
+ * This function finds only coalesce expressions of `LogicalExpression` node.
899
+ * @param {ASTNode} node The node to check.
900
+ * @returns {boolean} `true` if the node is `??`.
901
+ */
902
+ function isCoalesceExpression(node) {
903
+ return node.type === "LogicalExpression" && node.operator === "??";
904
+ }
905
+
906
+ /**
907
+ * Check if given two nodes are the pair of a logical expression and a coalesce expression.
908
+ * @param {ASTNode} left A node to check.
909
+ * @param {ASTNode} right Another node to check.
910
+ * @returns {boolean} `true` if the two nodes are the pair of a logical expression and a coalesce expression.
911
+ */
912
+ function isMixedLogicalAndCoalesceExpressions(left, right) {
913
+ return (
914
+ (isLogicalExpression(left) && isCoalesceExpression(right)) ||
915
+ (isCoalesceExpression(left) && isLogicalExpression(right))
916
+ );
917
+ }
918
+
919
+ /**
920
+ * Checks if the given operator is a logical assignment operator.
921
+ * @param {string} operator The operator to check.
922
+ * @returns {boolean} `true` if the operator is a logical assignment operator.
923
+ */
924
+ function isLogicalAssignmentOperator(operator) {
925
+ return LOGICAL_ASSIGNMENT_OPERATORS.has(operator);
926
+ }
927
+
928
+ /**
929
+ * Get the colon token of the given SwitchCase node.
930
+ * @param {ASTNode} node The SwitchCase node to get.
931
+ * @param {SourceCode} sourceCode The source code object to get tokens.
932
+ * @returns {Token} The colon token of the node.
933
+ */
934
+ function getSwitchCaseColonToken(node, sourceCode) {
935
+ if (node.test) {
936
+ return sourceCode.getTokenAfter(node.test, isColonToken);
937
+ }
938
+ return sourceCode.getFirstToken(node, 1);
939
+ }
940
+
941
+ /**
942
+ * Gets ESM module export name represented by the given node.
943
+ * @param {ASTNode} node `Identifier` or string `Literal` node in a position
944
+ * that represents a module export name:
945
+ * - `ImportSpecifier#imported`
946
+ * - `ExportSpecifier#local` (if it is a re-export from another module)
947
+ * - `ExportSpecifier#exported`
948
+ * - `ExportAllDeclaration#exported`
949
+ * @returns {string} The module export name.
950
+ */
951
+ function getModuleExportName(node) {
952
+ if (node.type === "Identifier") {
953
+ return node.name;
954
+ }
955
+
956
+ // string literal
957
+ return node.value;
958
+ }
959
+
960
+ /**
961
+ * Returns literal's value converted to the Boolean type
962
+ * @param {ASTNode} node any `Literal` node
963
+ * @returns {boolean | null} `true` when node is truthy, `false` when node is falsy,
964
+ * `null` when it cannot be determined.
965
+ */
966
+ function getBooleanValue(node) {
967
+ if (node.value === null) {
968
+ /*
969
+ * it might be a null literal or bigint/regex literal in unsupported environments .
970
+ * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es5.md#regexpliteral
971
+ * https://github.com/estree/estree/blob/14df8a024956ea289bd55b9c2226a1d5b8a473ee/es2020.md#bigintliteral
972
+ */
973
+
974
+ if (node.raw === "null") {
975
+ return false;
976
+ }
977
+
978
+ // regex is always truthy
979
+ if (typeof node.regex === "object") {
980
+ return true;
981
+ }
982
+
983
+ return null;
984
+ }
985
+
986
+ return !!node.value;
987
+ }
988
+
989
+ /**
990
+ * Checks if a branch node of LogicalExpression short circuits the whole condition
991
+ * @param {ASTNode} node The branch of main condition which needs to be checked
992
+ * @param {string} operator The operator of the main LogicalExpression.
993
+ * @returns {boolean} true when condition short circuits whole condition
994
+ */
995
+ function isLogicalIdentity(node, operator) {
996
+ switch (node.type) {
997
+ case "Literal":
998
+ return (
999
+ (operator === "||" && getBooleanValue(node) === true) ||
1000
+ (operator === "&&" && getBooleanValue(node) === false)
1001
+ );
1002
+
1003
+ case "UnaryExpression":
1004
+ return operator === "&&" && node.operator === "void";
1005
+
1006
+ case "LogicalExpression":
1007
+ /*
1008
+ * handles `a && false || b`
1009
+ * `false` is an identity element of `&&` but not `||`
1010
+ */
1011
+ return (
1012
+ operator === node.operator &&
1013
+ (isLogicalIdentity(node.left, operator) ||
1014
+ isLogicalIdentity(node.right, operator))
1015
+ );
1016
+
1017
+ case "AssignmentExpression":
1018
+ return (
1019
+ ["||=", "&&="].includes(node.operator) &&
1020
+ operator === node.operator.slice(0, -1) &&
1021
+ isLogicalIdentity(node.right, operator)
1022
+ );
1023
+
1024
+ // no default
1025
+ }
1026
+ return false;
1027
+ }
1028
+
1029
+ /**
1030
+ * Checks if an identifier is a reference to a global variable.
1031
+ * @param {Scope} scope The scope in which the identifier is referenced.
1032
+ * @param {ASTNode} node An identifier node to check.
1033
+ * @returns {boolean} `true` if the identifier is a reference to a global variable.
1034
+ */
1035
+ function isReferenceToGlobalVariable(scope, node) {
1036
+ const reference = scope.references.find(ref => ref.identifier === node);
1037
+
1038
+ return Boolean(
1039
+ reference &&
1040
+ reference.resolved &&
1041
+ reference.resolved.scope.type === "global" &&
1042
+ reference.resolved.defs.length === 0,
1043
+ );
1044
+ }
1045
+
1046
+ /**
1047
+ * Checks if a node has a constant truthiness value.
1048
+ * @param {Scope} scope Scope in which the node appears.
1049
+ * @param {ASTNode} node The AST node to check.
1050
+ * @param {boolean} inBooleanPosition `true` if checking the test of a
1051
+ * condition. `false` in all other cases. When `false`, checks if -- for
1052
+ * both string and number -- if coerced to that type, the value will
1053
+ * be constant.
1054
+ * @returns {boolean} true when node's truthiness is constant
1055
+ * @private
1056
+ */
1057
+ function isConstant(scope, node, inBooleanPosition) {
1058
+ // node.elements can return null values in the case of sparse arrays ex. [,]
1059
+ if (!node) {
1060
+ return true;
1061
+ }
1062
+ switch (node.type) {
1063
+ case "Literal":
1064
+ case "ArrowFunctionExpression":
1065
+ case "FunctionExpression":
1066
+ return true;
1067
+ case "ClassExpression":
1068
+ case "ObjectExpression":
1069
+ /**
1070
+ * In theory objects like:
1071
+ *
1072
+ * `{toString: () => a}`
1073
+ * `{valueOf: () => a}`
1074
+ *
1075
+ * Or a classes like:
1076
+ *
1077
+ * `class { static toString() { return a } }`
1078
+ * `class { static valueOf() { return a } }`
1079
+ *
1080
+ * Are not constant verifiably when `inBooleanPosition` is
1081
+ * false, but it's an edge case we've opted not to handle.
1082
+ */
1083
+ return true;
1084
+ case "TemplateLiteral":
1085
+ return (
1086
+ (inBooleanPosition &&
1087
+ node.quasis.some(quasi => quasi.value.cooked.length)) ||
1088
+ node.expressions.every(exp => isConstant(scope, exp, false))
1089
+ );
1090
+
1091
+ case "ArrayExpression": {
1092
+ if (!inBooleanPosition) {
1093
+ return node.elements.every(element =>
1094
+ isConstant(scope, element, false),
1095
+ );
1096
+ }
1097
+ return true;
1098
+ }
1099
+
1100
+ case "UnaryExpression":
1101
+ if (
1102
+ node.operator === "void" ||
1103
+ (node.operator === "typeof" && inBooleanPosition)
1104
+ ) {
1105
+ return true;
1106
+ }
1107
+
1108
+ if (node.operator === "!") {
1109
+ return isConstant(scope, node.argument, true);
1110
+ }
1111
+
1112
+ return isConstant(scope, node.argument, false);
1113
+
1114
+ case "BinaryExpression":
1115
+ return (
1116
+ isConstant(scope, node.left, false) &&
1117
+ isConstant(scope, node.right, false) &&
1118
+ node.operator !== "in"
1119
+ );
1120
+
1121
+ case "LogicalExpression": {
1122
+ const isLeftConstant = isConstant(
1123
+ scope,
1124
+ node.left,
1125
+ inBooleanPosition,
1126
+ );
1127
+ const isRightConstant = isConstant(
1128
+ scope,
1129
+ node.right,
1130
+ inBooleanPosition,
1131
+ );
1132
+ const isLeftShortCircuit =
1133
+ isLeftConstant && isLogicalIdentity(node.left, node.operator);
1134
+ const isRightShortCircuit =
1135
+ inBooleanPosition &&
1136
+ isRightConstant &&
1137
+ isLogicalIdentity(node.right, node.operator);
1138
+
1139
+ return (
1140
+ (isLeftConstant && isRightConstant) ||
1141
+ isLeftShortCircuit ||
1142
+ isRightShortCircuit
1143
+ );
1144
+ }
1145
+ case "NewExpression":
1146
+ return inBooleanPosition;
1147
+ case "AssignmentExpression":
1148
+ if (node.operator === "=") {
1149
+ return isConstant(scope, node.right, inBooleanPosition);
1150
+ }
1151
+
1152
+ if (["||=", "&&="].includes(node.operator) && inBooleanPosition) {
1153
+ return isLogicalIdentity(
1154
+ node.right,
1155
+ node.operator.slice(0, -1),
1156
+ );
1157
+ }
1158
+
1159
+ return false;
1160
+
1161
+ case "SequenceExpression":
1162
+ return isConstant(
1163
+ scope,
1164
+ node.expressions.at(-1),
1165
+ inBooleanPosition,
1166
+ );
1167
+ case "SpreadElement":
1168
+ return isConstant(scope, node.argument, inBooleanPosition);
1169
+ case "CallExpression":
1170
+ if (
1171
+ node.callee.type === "Identifier" &&
1172
+ node.callee.name === "Boolean"
1173
+ ) {
1174
+ if (
1175
+ node.arguments.length === 0 ||
1176
+ isConstant(scope, node.arguments[0], true)
1177
+ ) {
1178
+ return isReferenceToGlobalVariable(scope, node.callee);
1179
+ }
1180
+ }
1181
+ return false;
1182
+ case "Identifier":
1183
+ return (
1184
+ node.name === "undefined" &&
1185
+ isReferenceToGlobalVariable(scope, node)
1186
+ );
1187
+
1188
+ // no default
1189
+ }
1190
+ return false;
1191
+ }
1192
+
1193
+ /**
1194
+ * Checks whether a node is an ExpressionStatement at the top level of a file, function body, or TypeScript module block.
1195
+ * A top-level ExpressionStatement node is a directive if it contains a single unparenthesized
1196
+ * string literal and if it occurs either as the first sibling or immediately after another
1197
+ * directive.
1198
+ * @param {ASTNode} node The node to check.
1199
+ * @returns {boolean} Whether or not the node is an ExpressionStatement at the top level of a
1200
+ * file, function body, or TypeScript module block.
1201
+ */
1202
+ function isTopLevelExpressionStatement(node) {
1203
+ if (node.type !== "ExpressionStatement") {
1204
+ return false;
1205
+ }
1206
+ const parent = node.parent;
1207
+
1208
+ return (
1209
+ parent.type === "Program" ||
1210
+ parent.type === "TSModuleBlock" ||
1211
+ (parent.type === "BlockStatement" && isFunction(parent.parent))
1212
+ );
1213
+ }
1214
+
1215
+ /**
1216
+ * Check whether the given node is a part of a directive prologue or not.
1217
+ * @param {ASTNode} node The node to check.
1218
+ * @returns {boolean} `true` if the node is a part of directive prologue.
1219
+ */
1220
+ function isDirective(node) {
1221
+ return (
1222
+ node.type === "ExpressionStatement" &&
1223
+ typeof node.directive === "string"
1224
+ );
1225
+ }
1226
+
1227
+ /**
1228
+ * Tests if a node appears at the beginning of an ancestor ExpressionStatement node.
1229
+ * @param {ASTNode} node The node to check.
1230
+ * @returns {boolean} Whether the node appears at the beginning of an ancestor ExpressionStatement node.
1231
+ */
1232
+ function isStartOfExpressionStatement(node) {
1233
+ const start = node.range[0];
1234
+ let ancestor = node;
1235
+
1236
+ while ((ancestor = ancestor.parent) && ancestor.range[0] === start) {
1237
+ if (ancestor.type === "ExpressionStatement") {
1238
+ return true;
1239
+ }
1240
+ }
1241
+ return false;
1242
+ }
1243
+
1244
+ /**
1245
+ * Determines whether an opening parenthesis `(`, bracket `[` or backtick ``` ` ``` needs to be preceded by a semicolon.
1246
+ * This opening parenthesis or bracket should be at the start of an `ExpressionStatement`, a `MethodDefinition` or at
1247
+ * the start of the body of an `ArrowFunctionExpression`.
1248
+ * @type {(sourceCode: SourceCode, node: ASTNode) => boolean}
1249
+ * @param {SourceCode} sourceCode The source code object.
1250
+ * @param {ASTNode} node A node at the position where an opening parenthesis or bracket will be inserted.
1251
+ * @returns {boolean} Whether a semicolon is required before the opening parenthesis or bracket.
1252
+ */
1253
+ let needsPrecedingSemicolon;
1254
+
1255
+ {
1256
+ const BREAK_OR_CONTINUE = new Set(["BreakStatement", "ContinueStatement"]);
1257
+
1258
+ // Declaration types that cannot be continued by a punctuator when ending with a string Literal that is a direct child.
1259
+ const DECLARATIONS = new Set([
1260
+ "ExportAllDeclaration",
1261
+ "ExportNamedDeclaration",
1262
+ "ImportDeclaration",
1263
+ ]);
1264
+
1265
+ const IDENTIFIER_OR_KEYWORD = new Set(["Identifier", "Keyword"]);
1266
+
1267
+ // Keywords that can immediately precede an ExpressionStatement node, mapped to the their node types.
1268
+ const NODE_TYPES_BY_KEYWORD = {
1269
+ __proto__: null,
1270
+ break: "BreakStatement",
1271
+ continue: "ContinueStatement",
1272
+ debugger: "DebuggerStatement",
1273
+ do: "DoWhileStatement",
1274
+ else: "IfStatement",
1275
+ return: "ReturnStatement",
1276
+ yield: "YieldExpression",
1277
+ };
1278
+
1279
+ /*
1280
+ * Before an opening parenthesis, postfix `++` and `--` always trigger ASI;
1281
+ * the tokens `:`, `;`, `{` and `=>` don't expect a semicolon, as that would count as an empty statement.
1282
+ */
1283
+ const PUNCTUATORS = new Set([":", ";", "{", "=>", "++", "--"]);
1284
+
1285
+ /*
1286
+ * Statements that can contain an `ExpressionStatement` after a closing parenthesis.
1287
+ * DoWhileStatement is an exception in that it always triggers ASI after the closing parenthesis.
1288
+ */
1289
+ const STATEMENTS = new Set([
1290
+ "DoWhileStatement",
1291
+ "ForInStatement",
1292
+ "ForOfStatement",
1293
+ "ForStatement",
1294
+ "IfStatement",
1295
+ "WhileStatement",
1296
+ "WithStatement",
1297
+ ]);
1298
+
1299
+ const TS_TYPE_NODE_TYPES = new Set([
1300
+ "TSAsExpression",
1301
+ "TSSatisfiesExpression",
1302
+ "TSTypeAliasDeclaration",
1303
+ "TSTypeAnnotation",
1304
+ ]);
1305
+
1306
+ /**
1307
+ * Determines whether a specified node is inside a TypeScript type context.
1308
+ * @param {ASTNode} node The node to check.
1309
+ * @returns {boolean} Whether the node is inside a TypeScript type context.
1310
+ */
1311
+ function isInType(node) {
1312
+ for (let currNode = node; ; ) {
1313
+ const { parent } = currNode;
1314
+ if (!parent) {
1315
+ break;
1316
+ }
1317
+ if (
1318
+ TS_TYPE_NODE_TYPES.has(parent.type) &&
1319
+ currNode === parent.typeAnnotation
1320
+ ) {
1321
+ return true;
1322
+ }
1323
+ currNode = parent;
1324
+ }
1325
+ return false;
1326
+ }
1327
+
1328
+ needsPrecedingSemicolon = function (sourceCode, node) {
1329
+ const prevToken = sourceCode.getTokenBefore(node);
1330
+
1331
+ if (
1332
+ !prevToken ||
1333
+ (prevToken.type === "Punctuator" &&
1334
+ PUNCTUATORS.has(prevToken.value))
1335
+ ) {
1336
+ return false;
1337
+ }
1338
+
1339
+ const prevNode = sourceCode.getNodeByRangeIndex(prevToken.range[0]);
1340
+
1341
+ if (
1342
+ prevNode.type === "TSDeclareFunction" ||
1343
+ prevNode.parent.type === "TSImportEqualsDeclaration" ||
1344
+ prevNode.parent.parent?.type === "TSImportEqualsDeclaration" ||
1345
+ TS_TYPE_NODE_TYPES.has(prevNode.type) ||
1346
+ isInType(prevNode)
1347
+ ) {
1348
+ return false;
1349
+ }
1350
+
1351
+ if (isClosingParenToken(prevToken)) {
1352
+ return !STATEMENTS.has(prevNode.type);
1353
+ }
1354
+
1355
+ if (isClosingBraceToken(prevToken)) {
1356
+ return (
1357
+ (prevNode.type === "BlockStatement" &&
1358
+ prevNode.parent.type === "FunctionExpression" &&
1359
+ prevNode.parent.parent.type !== "MethodDefinition") ||
1360
+ (prevNode.type === "ClassBody" &&
1361
+ prevNode.parent.type === "ClassExpression") ||
1362
+ prevNode.type === "ObjectExpression"
1363
+ );
1364
+ }
1365
+
1366
+ if (IDENTIFIER_OR_KEYWORD.has(prevToken.type)) {
1367
+ if (
1368
+ prevNode.parent.type === "VariableDeclarator" &&
1369
+ !prevNode.parent.init
1370
+ ) {
1371
+ return false;
1372
+ }
1373
+ if (BREAK_OR_CONTINUE.has(prevNode.parent.type)) {
1374
+ return false;
1375
+ }
1376
+
1377
+ const keyword = prevToken.value;
1378
+ const nodeType = NODE_TYPES_BY_KEYWORD[keyword];
1379
+
1380
+ return prevNode.type !== nodeType;
1381
+ }
1382
+
1383
+ if (prevToken.type === "String") {
1384
+ return !DECLARATIONS.has(prevNode.parent.type);
1385
+ }
1386
+
1387
+ return true;
1388
+ };
1389
+ }
1390
+
1391
+ /**
1392
+ * Checks if a node is used as an import attribute key, either in a static or dynamic import.
1393
+ * @param {ASTNode} node The node to check.
1394
+ * @returns {boolean} Whether the node is used as an import attribute key.
1395
+ */
1396
+ function isImportAttributeKey(node) {
1397
+ const { parent } = node;
1398
+
1399
+ // static import/re-export
1400
+ if (parent.type === "ImportAttribute" && parent.key === node) {
1401
+ return true;
1402
+ }
1403
+
1404
+ // dynamic import
1405
+ if (
1406
+ parent.type === "Property" &&
1407
+ !parent.computed &&
1408
+ (parent.key === node ||
1409
+ (parent.value === node && parent.shorthand && !parent.method)) &&
1410
+ parent.parent.type === "ObjectExpression"
1411
+ ) {
1412
+ const objectExpression = parent.parent;
1413
+ const objectExpressionParent = objectExpression.parent;
1414
+
1415
+ if (
1416
+ objectExpressionParent.type === "ImportExpression" &&
1417
+ objectExpressionParent.options === objectExpression
1418
+ ) {
1419
+ return true;
1420
+ }
1421
+
1422
+ // nested key
1423
+ if (
1424
+ objectExpressionParent.type === "Property" &&
1425
+ objectExpressionParent.value === objectExpression
1426
+ ) {
1427
+ return isImportAttributeKey(objectExpressionParent.key);
1428
+ }
1429
+ }
1430
+
1431
+ return false;
1432
+ }
1433
+
1434
+ //------------------------------------------------------------------------------
1435
+ // Public Interface
1436
+ //------------------------------------------------------------------------------
1437
+
1438
+ module.exports = {
1439
+ COMMENTS_IGNORE_PATTERN,
1440
+ LINEBREAKS,
1441
+ LINEBREAK_MATCHER: lineBreakPattern,
1442
+ SHEBANG_MATCHER: shebangPattern,
1443
+ STATEMENT_LIST_PARENTS,
1444
+ ECMASCRIPT_GLOBALS,
1445
+
1446
+ /**
1447
+ * Determines whether two adjacent tokens are on the same line.
1448
+ * @param {Object} left The left token object.
1449
+ * @param {Object} right The right token object.
1450
+ * @returns {boolean} Whether or not the tokens are on the same line.
1451
+ * @public
1452
+ */
1453
+ isTokenOnSameLine(left, right) {
1454
+ return left.loc.end.line === right.loc.start.line;
1455
+ },
1456
+
1457
+ isNullOrUndefined,
1458
+ isCallee,
1459
+ isES5Constructor,
1460
+ getUpperFunction,
1461
+ isFunction,
1462
+ isLoop,
1463
+ isInLoop,
1464
+ isArrayFromMethod,
1465
+ isParenthesised,
1466
+ createGlobalLinebreakMatcher,
1467
+ equalTokens,
1468
+
1469
+ isArrowToken,
1470
+ isClosingBraceToken,
1471
+ isClosingBracketToken,
1472
+ isClosingParenToken,
1473
+ isColonToken,
1474
+ isCommaToken,
1475
+ isCommentToken,
1476
+ isDotToken,
1477
+ isQuestionDotToken,
1478
+ isKeywordToken,
1479
+ isNotClosingBraceToken: negate(isClosingBraceToken),
1480
+ isNotClosingBracketToken: negate(isClosingBracketToken),
1481
+ isNotClosingParenToken: negate(isClosingParenToken),
1482
+ isNotColonToken: negate(isColonToken),
1483
+ isNotCommaToken: negate(isCommaToken),
1484
+ isNotDotToken: negate(isDotToken),
1485
+ isNotQuestionDotToken: negate(isQuestionDotToken),
1486
+ isNotOpeningBraceToken: negate(isOpeningBraceToken),
1487
+ isNotOpeningBracketToken: negate(isOpeningBracketToken),
1488
+ isNotOpeningParenToken: negate(isOpeningParenToken),
1489
+ isNotSemicolonToken: negate(isSemicolonToken),
1490
+ isOpeningBraceToken,
1491
+ isOpeningBracketToken,
1492
+ isOpeningParenToken,
1493
+ isSemicolonToken,
1494
+ isEqToken,
1495
+
1496
+ /**
1497
+ * Checks whether or not a given node is a string literal.
1498
+ * @param {ASTNode} node A node to check.
1499
+ * @returns {boolean} `true` if the node is a string literal.
1500
+ */
1501
+ isStringLiteral(node) {
1502
+ return (
1503
+ (node.type === "Literal" && typeof node.value === "string") ||
1504
+ node.type === "TemplateLiteral"
1505
+ );
1506
+ },
1507
+
1508
+ /**
1509
+ * Checks whether a given node is a breakable statement or not.
1510
+ * The node is breakable if the node is one of the following type:
1511
+ *
1512
+ * - DoWhileStatement
1513
+ * - ForInStatement
1514
+ * - ForOfStatement
1515
+ * - ForStatement
1516
+ * - SwitchStatement
1517
+ * - WhileStatement
1518
+ * @param {ASTNode} node A node to check.
1519
+ * @returns {boolean} `true` if the node is breakable.
1520
+ */
1521
+ isBreakableStatement(node) {
1522
+ return breakableTypePattern.test(node.type);
1523
+ },
1524
+
1525
+ /**
1526
+ * Gets references which are non initializer and writable.
1527
+ * @param {Reference[]} references An array of references.
1528
+ * @returns {Reference[]} An array of only references which are non initializer and writable.
1529
+ * @public
1530
+ */
1531
+ getModifyingReferences(references) {
1532
+ return references.filter(isModifyingReference);
1533
+ },
1534
+
1535
+ /**
1536
+ * Validate that a string passed in is surrounded by the specified character
1537
+ * @param {string} val The text to check.
1538
+ * @param {string} character The character to see if it's surrounded by.
1539
+ * @returns {boolean} True if the text is surrounded by the character, false if not.
1540
+ * @private
1541
+ */
1542
+ isSurroundedBy(val, character) {
1543
+ return val[0] === character && val.at(-1) === character;
1544
+ },
1545
+
1546
+ /**
1547
+ * Returns whether the provided node is an ESLint directive comment or not
1548
+ * @param {Line|Block} node The comment token to be checked
1549
+ * @returns {boolean} `true` if the node is an ESLint directive comment
1550
+ */
1551
+ isDirectiveComment(node) {
1552
+ const comment = node.value.trim();
1553
+
1554
+ return (
1555
+ (node.type === "Line" && comment.startsWith("eslint-")) ||
1556
+ (node.type === "Block" && ESLINT_DIRECTIVE_PATTERN.test(comment))
1557
+ );
1558
+ },
1559
+
1560
+ /**
1561
+ * Gets the trailing statement of a given node.
1562
+ *
1563
+ * if (code)
1564
+ * consequent;
1565
+ *
1566
+ * When taking this `IfStatement`, returns `consequent;` statement.
1567
+ * @param {ASTNode} A node to get.
1568
+ * @returns {ASTNode|null} The trailing statement's node.
1569
+ */
1570
+ getTrailingStatement: esutils.ast.trailingStatement,
1571
+
1572
+ /**
1573
+ * Finds the variable by a given name in a given scope and its upper scopes.
1574
+ * @param {eslint-scope.Scope} initScope A scope to start find.
1575
+ * @param {string} name A variable name to find.
1576
+ * @returns {eslint-scope.Variable|null} A found variable or `null`.
1577
+ */
1578
+ getVariableByName(initScope, name) {
1579
+ let scope = initScope;
1580
+
1581
+ while (scope) {
1582
+ const variable = scope.set.get(name);
1583
+
1584
+ if (variable) {
1585
+ return variable;
1586
+ }
1587
+
1588
+ scope = scope.upper;
1589
+ }
1590
+
1591
+ return null;
1592
+ },
1593
+
1594
+ /**
1595
+ * Checks whether or not a given function node is the default `this` binding.
1596
+ *
1597
+ * First, this checks the node:
1598
+ *
1599
+ * - The given node is not in `PropertyDefinition#value` position.
1600
+ * - The given node is not `StaticBlock`.
1601
+ * - The function name does not start with uppercase. It's a convention to capitalize the names
1602
+ * of constructor functions. This check is not performed if `capIsConstructor` is set to `false`.
1603
+ * - The function does not have a JSDoc comment that has a @this tag.
1604
+ *
1605
+ * Next, this checks the location of the node.
1606
+ * If the location is below, this judges `this` is valid.
1607
+ *
1608
+ * - The location is not on an object literal.
1609
+ * - The location is not assigned to a variable which starts with an uppercase letter. Applies to anonymous
1610
+ * functions only, as the name of the variable is considered to be the name of the function in this case.
1611
+ * This check is not performed if `capIsConstructor` is set to `false`.
1612
+ * - The location is not on an ES2015 class.
1613
+ * - Its `bind`/`call`/`apply` method is not called directly.
1614
+ * - The function is not a callback of array methods (such as `.forEach()`) if `thisArg` is given.
1615
+ * @param {ASTNode} node A function node to check. It also can be an implicit function, like `StaticBlock`
1616
+ * or any expression that is `PropertyDefinition#value` node.
1617
+ * @param {SourceCode} sourceCode A SourceCode instance to get comments.
1618
+ * @param {boolean} [capIsConstructor = true] `false` disables the assumption that functions which name starts
1619
+ * with an uppercase or are assigned to a variable which name starts with an uppercase are constructors.
1620
+ * @returns {boolean} The function node is the default `this` binding.
1621
+ */
1622
+ isDefaultThisBinding(node, sourceCode, { capIsConstructor = true } = {}) {
1623
+ /*
1624
+ * Class field initializers are implicit functions, but ESTree doesn't have the AST node of field initializers.
1625
+ * Therefore, A expression node at `PropertyDefinition#value` is a function.
1626
+ * In this case, `this` is always not default binding.
1627
+ */
1628
+ if (
1629
+ node.parent.type === "PropertyDefinition" &&
1630
+ node.parent.value === node
1631
+ ) {
1632
+ return false;
1633
+ }
1634
+
1635
+ // Class static blocks are implicit functions. In this case, `this` is always not default binding.
1636
+ if (node.type === "StaticBlock") {
1637
+ return false;
1638
+ }
1639
+
1640
+ // Check if the function has a parameter named `this`.
1641
+ if (
1642
+ (node.type === "FunctionDeclaration" ||
1643
+ node.type === "FunctionExpression") &&
1644
+ node.params.some(
1645
+ param => param.type === "Identifier" && param.name === "this",
1646
+ )
1647
+ ) {
1648
+ return false;
1649
+ }
1650
+
1651
+ if (
1652
+ (capIsConstructor && isES5Constructor(node)) ||
1653
+ hasJSDocThisTag(node, sourceCode)
1654
+ ) {
1655
+ return false;
1656
+ }
1657
+ const isAnonymous = node.id === null;
1658
+ let currentNode = node;
1659
+
1660
+ while (currentNode) {
1661
+ const parent = currentNode.parent;
1662
+
1663
+ switch (parent.type) {
1664
+ /*
1665
+ * Looks up the destination.
1666
+ * e.g., obj.foo = nativeFoo || function foo() { ... };
1667
+ */
1668
+ case "LogicalExpression":
1669
+ case "ConditionalExpression":
1670
+ case "ChainExpression":
1671
+ currentNode = parent;
1672
+ break;
1673
+
1674
+ /*
1675
+ * If the upper function is IIFE, checks the destination of the return value.
1676
+ * e.g.
1677
+ * obj.foo = (function() {
1678
+ * // setup...
1679
+ * return function foo() { ... };
1680
+ * })();
1681
+ * obj.foo = (() =>
1682
+ * function foo() { ... }
1683
+ * )();
1684
+ */
1685
+ case "ReturnStatement": {
1686
+ const func = getUpperFunction(parent);
1687
+
1688
+ if (func === null || !isCallee(func)) {
1689
+ return true;
1690
+ }
1691
+ currentNode = func.parent;
1692
+ break;
1693
+ }
1694
+ case "ArrowFunctionExpression":
1695
+ if (currentNode !== parent.body || !isCallee(parent)) {
1696
+ return true;
1697
+ }
1698
+ currentNode = parent.parent;
1699
+ break;
1700
+
1701
+ /*
1702
+ * e.g.
1703
+ * var obj = { foo() { ... } };
1704
+ * var obj = { foo: function() { ... } };
1705
+ * class A { constructor() { ... } }
1706
+ * class A { foo() { ... } }
1707
+ * class A { get foo() { ... } }
1708
+ * class A { set foo() { ... } }
1709
+ * class A { static foo() { ... } }
1710
+ * class A { foo = function() { ... } }
1711
+ */
1712
+ case "Property":
1713
+ case "PropertyDefinition":
1714
+ case "MethodDefinition":
1715
+ return parent.value !== currentNode;
1716
+
1717
+ /*
1718
+ * e.g.
1719
+ * obj.foo = function foo() { ... };
1720
+ * Foo = function() { ... };
1721
+ * [obj.foo = function foo() { ... }] = a;
1722
+ * [Foo = function() { ... }] = a;
1723
+ */
1724
+ case "AssignmentExpression":
1725
+ case "AssignmentPattern":
1726
+ if (parent.left.type === "MemberExpression") {
1727
+ return false;
1728
+ }
1729
+ if (
1730
+ capIsConstructor &&
1731
+ isAnonymous &&
1732
+ parent.left.type === "Identifier" &&
1733
+ startsWithUpperCase(parent.left.name)
1734
+ ) {
1735
+ return false;
1736
+ }
1737
+ return true;
1738
+
1739
+ /*
1740
+ * e.g.
1741
+ * var Foo = function() { ... };
1742
+ */
1743
+ case "VariableDeclarator":
1744
+ return !(
1745
+ capIsConstructor &&
1746
+ isAnonymous &&
1747
+ parent.init === currentNode &&
1748
+ parent.id.type === "Identifier" &&
1749
+ startsWithUpperCase(parent.id.name)
1750
+ );
1751
+
1752
+ /*
1753
+ * e.g.
1754
+ * var foo = function foo() { ... }.bind(obj);
1755
+ * (function foo() { ... }).call(obj);
1756
+ * (function foo() { ... }).apply(obj, []);
1757
+ */
1758
+ case "MemberExpression":
1759
+ if (
1760
+ parent.object === currentNode &&
1761
+ isSpecificMemberAccess(
1762
+ parent,
1763
+ null,
1764
+ bindOrCallOrApplyPattern,
1765
+ )
1766
+ ) {
1767
+ const maybeCalleeNode =
1768
+ parent.parent.type === "ChainExpression"
1769
+ ? parent.parent
1770
+ : parent;
1771
+
1772
+ return !(
1773
+ isCallee(maybeCalleeNode) &&
1774
+ maybeCalleeNode.parent.arguments.length >= 1 &&
1775
+ !isNullOrUndefined(
1776
+ maybeCalleeNode.parent.arguments[0],
1777
+ )
1778
+ );
1779
+ }
1780
+ return true;
1781
+
1782
+ /*
1783
+ * e.g.
1784
+ * Reflect.apply(function() {}, obj, []);
1785
+ * Array.from([], function() {}, obj);
1786
+ * list.forEach(function() {}, obj);
1787
+ */
1788
+ case "CallExpression":
1789
+ if (isReflectApply(parent.callee)) {
1790
+ return (
1791
+ parent.arguments.length !== 3 ||
1792
+ parent.arguments[0] !== currentNode ||
1793
+ isNullOrUndefined(parent.arguments[1])
1794
+ );
1795
+ }
1796
+ if (isArrayFromMethod(parent.callee)) {
1797
+ return (
1798
+ parent.arguments.length !== 3 ||
1799
+ parent.arguments[1] !== currentNode ||
1800
+ isNullOrUndefined(parent.arguments[2])
1801
+ );
1802
+ }
1803
+ if (isMethodWhichHasThisArg(parent.callee)) {
1804
+ return (
1805
+ parent.arguments.length !== 2 ||
1806
+ parent.arguments[0] !== currentNode ||
1807
+ isNullOrUndefined(parent.arguments[1])
1808
+ );
1809
+ }
1810
+ return true;
1811
+
1812
+ // Otherwise `this` is default.
1813
+ default:
1814
+ return true;
1815
+ }
1816
+ }
1817
+
1818
+ /* c8 ignore next */
1819
+ return true;
1820
+ },
1821
+
1822
+ /**
1823
+ * Get the precedence level based on the node type
1824
+ * @param {ASTNode} node node to evaluate
1825
+ * @returns {number} precedence level
1826
+ * @private
1827
+ */
1828
+ getPrecedence(node) {
1829
+ switch (node.type) {
1830
+ case "SequenceExpression":
1831
+ return 0;
1832
+
1833
+ case "AssignmentExpression":
1834
+ case "ArrowFunctionExpression":
1835
+ case "YieldExpression":
1836
+ return 1;
1837
+
1838
+ case "ConditionalExpression":
1839
+ return 3;
1840
+
1841
+ case "LogicalExpression":
1842
+ switch (node.operator) {
1843
+ case "||":
1844
+ case "??":
1845
+ return 4;
1846
+ case "&&":
1847
+ return 5;
1848
+
1849
+ // no default
1850
+ }
1851
+
1852
+ /* falls through */
1853
+
1854
+ case "BinaryExpression":
1855
+ switch (node.operator) {
1856
+ case "|":
1857
+ return 6;
1858
+ case "^":
1859
+ return 7;
1860
+ case "&":
1861
+ return 8;
1862
+ case "==":
1863
+ case "!=":
1864
+ case "===":
1865
+ case "!==":
1866
+ return 9;
1867
+ case "<":
1868
+ case "<=":
1869
+ case ">":
1870
+ case ">=":
1871
+ case "in":
1872
+ case "instanceof":
1873
+ return 10;
1874
+ case "<<":
1875
+ case ">>":
1876
+ case ">>>":
1877
+ return 11;
1878
+ case "+":
1879
+ case "-":
1880
+ return 12;
1881
+ case "*":
1882
+ case "/":
1883
+ case "%":
1884
+ return 13;
1885
+ case "**":
1886
+ return 15;
1887
+
1888
+ // no default
1889
+ }
1890
+
1891
+ /* falls through */
1892
+
1893
+ case "UnaryExpression":
1894
+ case "AwaitExpression":
1895
+ return 16;
1896
+
1897
+ case "UpdateExpression":
1898
+ return 17;
1899
+
1900
+ case "CallExpression":
1901
+ case "ChainExpression":
1902
+ case "ImportExpression":
1903
+ return 18;
1904
+
1905
+ case "NewExpression":
1906
+ return 19;
1907
+
1908
+ default:
1909
+ if (node.type in eslintVisitorKeys) {
1910
+ return 20;
1911
+ }
1912
+
1913
+ /*
1914
+ * if the node is not a standard node that we know about, then assume it has the lowest precedence
1915
+ * this will mean that rules will wrap unknown nodes in parentheses where applicable instead of
1916
+ * unwrapping them and potentially changing the meaning of the code or introducing a syntax error.
1917
+ */
1918
+ return -1;
1919
+ }
1920
+ },
1921
+
1922
+ /**
1923
+ * Checks whether the given node is an empty block node or not.
1924
+ * @param {ASTNode|null} node The node to check.
1925
+ * @returns {boolean} `true` if the node is an empty block.
1926
+ */
1927
+ isEmptyBlock(node) {
1928
+ return Boolean(
1929
+ node && node.type === "BlockStatement" && node.body.length === 0,
1930
+ );
1931
+ },
1932
+
1933
+ /**
1934
+ * Checks whether the given node is an empty function node or not.
1935
+ * @param {ASTNode|null} node The node to check.
1936
+ * @returns {boolean} `true` if the node is an empty function.
1937
+ */
1938
+ isEmptyFunction(node) {
1939
+ return isFunction(node) && module.exports.isEmptyBlock(node.body);
1940
+ },
1941
+
1942
+ /**
1943
+ * Get directives from directive prologue of a Program or Function node.
1944
+ * @param {ASTNode} node The node to check.
1945
+ * @returns {ASTNode[]} The directives found in the directive prologue.
1946
+ */
1947
+ getDirectivePrologue(node) {
1948
+ const directives = [];
1949
+
1950
+ // Directive prologues only occur at the top of files or functions.
1951
+ if (
1952
+ node.type === "Program" ||
1953
+ node.type === "FunctionDeclaration" ||
1954
+ node.type === "FunctionExpression" ||
1955
+ /*
1956
+ * Do not check arrow functions with implicit return.
1957
+ * `() => "use strict";` returns the string `"use strict"`.
1958
+ */
1959
+ (node.type === "ArrowFunctionExpression" &&
1960
+ node.body.type === "BlockStatement")
1961
+ ) {
1962
+ const statements =
1963
+ node.type === "Program" ? node.body : node.body.body;
1964
+
1965
+ for (const statement of statements) {
1966
+ if (
1967
+ statement.type === "ExpressionStatement" &&
1968
+ statement.expression.type === "Literal"
1969
+ ) {
1970
+ directives.push(statement);
1971
+ } else {
1972
+ break;
1973
+ }
1974
+ }
1975
+ }
1976
+
1977
+ return directives;
1978
+ },
1979
+
1980
+ /**
1981
+ * Determines whether this node is a decimal integer literal. If a node is a decimal integer literal, a dot added
1982
+ * after the node will be parsed as a decimal point, rather than a property-access dot.
1983
+ * @param {ASTNode} node The node to check.
1984
+ * @returns {boolean} `true` if this node is a decimal integer.
1985
+ * @example
1986
+ *
1987
+ * 0 // true
1988
+ * 5 // true
1989
+ * 50 // true
1990
+ * 5_000 // true
1991
+ * 1_234_56 // true
1992
+ * 08 // true
1993
+ * 0192 // true
1994
+ * 5. // false
1995
+ * .5 // false
1996
+ * 5.0 // false
1997
+ * 5.00_00 // false
1998
+ * 05 // false
1999
+ * 0x5 // false
2000
+ * 0b101 // false
2001
+ * 0b11_01 // false
2002
+ * 0o5 // false
2003
+ * 5e0 // false
2004
+ * 5e1_000 // false
2005
+ * 5n // false
2006
+ * 1_000n // false
2007
+ * "5" // false
2008
+ *
2009
+ */
2010
+ isDecimalInteger(node) {
2011
+ return (
2012
+ node.type === "Literal" &&
2013
+ typeof node.value === "number" &&
2014
+ DECIMAL_INTEGER_PATTERN.test(node.raw)
2015
+ );
2016
+ },
2017
+
2018
+ /**
2019
+ * Determines whether this token is a decimal integer numeric token.
2020
+ * This is similar to isDecimalInteger(), but for tokens.
2021
+ * @param {Token} token The token to check.
2022
+ * @returns {boolean} `true` if this token is a decimal integer.
2023
+ */
2024
+ isDecimalIntegerNumericToken(token) {
2025
+ return (
2026
+ token.type === "Numeric" &&
2027
+ DECIMAL_INTEGER_PATTERN.test(token.value)
2028
+ );
2029
+ },
2030
+
2031
+ /**
2032
+ * Gets the name and kind of the given function node.
2033
+ *
2034
+ * - `function foo() {}` .................... `function 'foo'`
2035
+ * - `(function foo() {})` .................. `function 'foo'`
2036
+ * - `(function() {})` ...................... `function`
2037
+ * - `function* foo() {}` ................... `generator function 'foo'`
2038
+ * - `(function* foo() {})` ................. `generator function 'foo'`
2039
+ * - `(function*() {})` ..................... `generator function`
2040
+ * - `() => {}` ............................. `arrow function`
2041
+ * - `async () => {}` ....................... `async arrow function`
2042
+ * - `({ foo: function foo() {} })` ......... `method 'foo'`
2043
+ * - `({ foo: function() {} })` ............. `method 'foo'`
2044
+ * - `({ ['foo']: function() {} })` ......... `method 'foo'`
2045
+ * - `({ [foo]: function() {} })` ........... `method`
2046
+ * - `({ foo() {} })` ....................... `method 'foo'`
2047
+ * - `({ foo: function* foo() {} })` ........ `generator method 'foo'`
2048
+ * - `({ foo: function*() {} })` ............ `generator method 'foo'`
2049
+ * - `({ ['foo']: function*() {} })` ........ `generator method 'foo'`
2050
+ * - `({ [foo]: function*() {} })` .......... `generator method`
2051
+ * - `({ *foo() {} })` ...................... `generator method 'foo'`
2052
+ * - `({ foo: async function foo() {} })` ... `async method 'foo'`
2053
+ * - `({ foo: async function() {} })` ....... `async method 'foo'`
2054
+ * - `({ ['foo']: async function() {} })` ... `async method 'foo'`
2055
+ * - `({ [foo]: async function() {} })` ..... `async method`
2056
+ * - `({ async foo() {} })` ................. `async method 'foo'`
2057
+ * - `({ get foo() {} })` ................... `getter 'foo'`
2058
+ * - `({ set foo(a) {} })` .................. `setter 'foo'`
2059
+ * - `class A { constructor() {} }` ......... `constructor`
2060
+ * - `class A { foo() {} }` ................. `method 'foo'`
2061
+ * - `class A { *foo() {} }` ................ `generator method 'foo'`
2062
+ * - `class A { async foo() {} }` ........... `async method 'foo'`
2063
+ * - `class A { ['foo']() {} }` ............. `method 'foo'`
2064
+ * - `class A { *['foo']() {} }` ............ `generator method 'foo'`
2065
+ * - `class A { async ['foo']() {} }` ....... `async method 'foo'`
2066
+ * - `class A { [foo]() {} }` ............... `method`
2067
+ * - `class A { *[foo]() {} }` .............. `generator method`
2068
+ * - `class A { async [foo]() {} }` ......... `async method`
2069
+ * - `class A { get foo() {} }` ............. `getter 'foo'`
2070
+ * - `class A { set foo(a) {} }` ............ `setter 'foo'`
2071
+ * - `class A { static foo() {} }` .......... `static method 'foo'`
2072
+ * - `class A { static *foo() {} }` ......... `static generator method 'foo'`
2073
+ * - `class A { static async foo() {} }` .... `static async method 'foo'`
2074
+ * - `class A { static get foo() {} }` ...... `static getter 'foo'`
2075
+ * - `class A { static set foo(a) {} }` ..... `static setter 'foo'`
2076
+ * - `class A { foo = () => {}; }` .......... `method 'foo'`
2077
+ * - `class A { foo = function() {}; }` ..... `method 'foo'`
2078
+ * - `class A { foo = function bar() {}; }` . `method 'foo'`
2079
+ * - `class A { static foo = () => {}; }` ... `static method 'foo'`
2080
+ * - `class A { '#foo' = () => {}; }` ....... `method '#foo'`
2081
+ * - `class A { #foo = () => {}; }` ......... `private method #foo`
2082
+ * - `class A { static #foo = () => {}; }` .. `static private method #foo`
2083
+ * - `class A { '#foo'() {} }` .............. `method '#foo'`
2084
+ * - `class A { #foo() {} }` ................ `private method #foo`
2085
+ * - `class A { static #foo() {} }` ......... `static private method #foo`
2086
+ * @param {ASTNode} node The function node to get.
2087
+ * @returns {string} The name and kind of the function node.
2088
+ */
2089
+ getFunctionNameWithKind(node) {
2090
+ const parent = node.parent;
2091
+ const tokens = [];
2092
+
2093
+ if (
2094
+ parent.type === "MethodDefinition" ||
2095
+ parent.type === "PropertyDefinition" ||
2096
+ node.type === "TSPropertySignature" ||
2097
+ node.type === "TSMethodSignature"
2098
+ ) {
2099
+ // The proposal uses `static` word consistently before visibility words: https://github.com/tc39/proposal-static-class-features
2100
+ if (parent.static) {
2101
+ tokens.push("static");
2102
+ }
2103
+ if (!parent.computed && parent.key?.type === "PrivateIdentifier") {
2104
+ tokens.push("private");
2105
+ }
2106
+ }
2107
+ if (node.async) {
2108
+ tokens.push("async");
2109
+ }
2110
+ if (node.generator) {
2111
+ tokens.push("generator");
2112
+ }
2113
+
2114
+ if (parent.type === "Property" || parent.type === "MethodDefinition") {
2115
+ if (parent.kind === "constructor") {
2116
+ return "constructor";
2117
+ }
2118
+ if (parent.kind === "get") {
2119
+ tokens.push("getter");
2120
+ } else if (parent.kind === "set") {
2121
+ tokens.push("setter");
2122
+ } else {
2123
+ tokens.push("method");
2124
+ }
2125
+ } else if (node.type === "TSMethodSignature") {
2126
+ if (node.kind === "get") {
2127
+ tokens.push("getter");
2128
+ } else if (node.kind === "set") {
2129
+ tokens.push("setter");
2130
+ } else {
2131
+ tokens.push("method");
2132
+ }
2133
+ } else if (parent.type === "PropertyDefinition") {
2134
+ tokens.push("method");
2135
+ } else {
2136
+ if (node.type === "ArrowFunctionExpression") {
2137
+ tokens.push("arrow");
2138
+ }
2139
+ tokens.push("function");
2140
+ }
2141
+
2142
+ if (
2143
+ parent.type === "Property" ||
2144
+ parent.type === "MethodDefinition" ||
2145
+ parent.type === "PropertyDefinition"
2146
+ ) {
2147
+ if (!parent.computed && parent.key.type === "PrivateIdentifier") {
2148
+ tokens.push(`#${parent.key.name}`);
2149
+ } else {
2150
+ const name = getStaticPropertyName(parent);
2151
+
2152
+ if (name !== null) {
2153
+ tokens.push(`'${name}'`);
2154
+ } else if (node.id) {
2155
+ tokens.push(`'${node.id.name}'`);
2156
+ }
2157
+ }
2158
+ } else if (node.type === "TSMethodSignature") {
2159
+ tokens.push(`'${getStaticPropertyName(node)}'`);
2160
+ } else if (node.id) {
2161
+ tokens.push(`'${node.id.name}'`);
2162
+ }
2163
+
2164
+ return tokens.join(" ");
2165
+ },
2166
+
2167
+ /**
2168
+ * Gets the location of the given function node for reporting.
2169
+ *
2170
+ * - `function foo() {}`
2171
+ * ^^^^^^^^^^^^
2172
+ * - `(function foo() {})`
2173
+ * ^^^^^^^^^^^^
2174
+ * - `(function() {})`
2175
+ * ^^^^^^^^
2176
+ * - `function* foo() {}`
2177
+ * ^^^^^^^^^^^^^
2178
+ * - `(function* foo() {})`
2179
+ * ^^^^^^^^^^^^^
2180
+ * - `(function*() {})`
2181
+ * ^^^^^^^^^
2182
+ * - `() => {}`
2183
+ * ^^
2184
+ * - `async () => {}`
2185
+ * ^^
2186
+ * - `({ foo: function foo() {} })`
2187
+ * ^^^^^^^^^^^^^^^^^
2188
+ * - `({ foo: function() {} })`
2189
+ * ^^^^^^^^^^^^^
2190
+ * - `({ ['foo']: function() {} })`
2191
+ * ^^^^^^^^^^^^^^^^^
2192
+ * - `({ [foo]: function() {} })`
2193
+ * ^^^^^^^^^^^^^^^
2194
+ * - `({ foo() {} })`
2195
+ * ^^^
2196
+ * - `({ foo: function* foo() {} })`
2197
+ * ^^^^^^^^^^^^^^^^^^
2198
+ * - `({ foo: function*() {} })`
2199
+ * ^^^^^^^^^^^^^^
2200
+ * - `({ ['foo']: function*() {} })`
2201
+ * ^^^^^^^^^^^^^^^^^^
2202
+ * - `({ [foo]: function*() {} })`
2203
+ * ^^^^^^^^^^^^^^^^
2204
+ * - `({ *foo() {} })`
2205
+ * ^^^^
2206
+ * - `({ foo: async function foo() {} })`
2207
+ * ^^^^^^^^^^^^^^^^^^^^^^^
2208
+ * - `({ foo: async function() {} })`
2209
+ * ^^^^^^^^^^^^^^^^^^^
2210
+ * - `({ ['foo']: async function() {} })`
2211
+ * ^^^^^^^^^^^^^^^^^^^^^^^
2212
+ * - `({ [foo]: async function() {} })`
2213
+ * ^^^^^^^^^^^^^^^^^^^^^
2214
+ * - `({ async foo() {} })`
2215
+ * ^^^^^^^^^
2216
+ * - `({ get foo() {} })`
2217
+ * ^^^^^^^
2218
+ * - `({ set foo(a) {} })`
2219
+ * ^^^^^^^
2220
+ * - `class A { constructor() {} }`
2221
+ * ^^^^^^^^^^^
2222
+ * - `class A { foo() {} }`
2223
+ * ^^^
2224
+ * - `class A { *foo() {} }`
2225
+ * ^^^^
2226
+ * - `class A { async foo() {} }`
2227
+ * ^^^^^^^^^
2228
+ * - `class A { ['foo']() {} }`
2229
+ * ^^^^^^^
2230
+ * - `class A { *['foo']() {} }`
2231
+ * ^^^^^^^^
2232
+ * - `class A { async ['foo']() {} }`
2233
+ * ^^^^^^^^^^^^^
2234
+ * - `class A { [foo]() {} }`
2235
+ * ^^^^^
2236
+ * - `class A { *[foo]() {} }`
2237
+ * ^^^^^^
2238
+ * - `class A { async [foo]() {} }`
2239
+ * ^^^^^^^^^^^
2240
+ * - `class A { get foo() {} }`
2241
+ * ^^^^^^^
2242
+ * - `class A { set foo(a) {} }`
2243
+ * ^^^^^^^
2244
+ * - `class A { static foo() {} }`
2245
+ * ^^^^^^^^^^
2246
+ * - `class A { static *foo() {} }`
2247
+ * ^^^^^^^^^^^
2248
+ * - `class A { static async foo() {} }`
2249
+ * ^^^^^^^^^^^^^^^^
2250
+ * - `class A { static get foo() {} }`
2251
+ * ^^^^^^^^^^^^^^
2252
+ * - `class A { static set foo(a) {} }`
2253
+ * ^^^^^^^^^^^^^^
2254
+ * - `class A { foo = function() {} }`
2255
+ * ^^^^^^^^^^^^^^
2256
+ * - `class A { static foo = function() {} }`
2257
+ * ^^^^^^^^^^^^^^^^^^^^^
2258
+ * - `class A { foo = (a, b) => {} }`
2259
+ * ^^^^^^
2260
+ * @param {ASTNode} node The function node to get.
2261
+ * @param {SourceCode} sourceCode The source code object to get tokens.
2262
+ * @returns {string} The location of the function node for reporting.
2263
+ */
2264
+ getFunctionHeadLoc(node, sourceCode) {
2265
+ const parent = node.parent;
2266
+ let start;
2267
+ let end;
2268
+
2269
+ if (
2270
+ parent.type === "Property" ||
2271
+ parent.type === "MethodDefinition" ||
2272
+ parent.type === "PropertyDefinition" ||
2273
+ parent.type === "TSPropertySignature" ||
2274
+ parent.type === "TSMethodSignature"
2275
+ ) {
2276
+ start = parent.loc.start;
2277
+ end = getOpeningParenOfParams(node, sourceCode).loc.start;
2278
+ } else if (node.type === "ArrowFunctionExpression") {
2279
+ const arrowToken = sourceCode.getTokenBefore(
2280
+ node.body,
2281
+ isArrowToken,
2282
+ );
2283
+
2284
+ start = arrowToken.loc.start;
2285
+ end = arrowToken.loc.end;
2286
+ } else {
2287
+ start = node.loc.start;
2288
+ end = getOpeningParenOfParams(node, sourceCode).loc.start;
2289
+ }
2290
+
2291
+ return {
2292
+ start: Object.assign({}, start),
2293
+ end: Object.assign({}, end),
2294
+ };
2295
+ },
2296
+
2297
+ /**
2298
+ * Gets next location when the result is not out of bound, otherwise returns null.
2299
+ *
2300
+ * Assumptions:
2301
+ *
2302
+ * - The given location represents a valid location in the given source code.
2303
+ * - Columns are 0-based.
2304
+ * - Lines are 1-based.
2305
+ * - Column immediately after the last character in a line (not incl. linebreaks) is considered to be a valid location.
2306
+ * - If the source code ends with a linebreak, `sourceCode.lines` array will have an extra element (empty string) at the end.
2307
+ * The start (column 0) of that extra line is considered to be a valid location.
2308
+ *
2309
+ * Examples of successive locations (line, column):
2310
+ *
2311
+ * code: foo
2312
+ * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> null
2313
+ *
2314
+ * code: foo<LF>
2315
+ * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
2316
+ *
2317
+ * code: foo<CR><LF>
2318
+ * locations: (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 0) -> null
2319
+ *
2320
+ * code: a<LF>b
2321
+ * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> null
2322
+ *
2323
+ * code: a<LF>b<LF>
2324
+ * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
2325
+ *
2326
+ * code: a<CR><LF>b<CR><LF>
2327
+ * locations: (1, 0) -> (1, 1) -> (2, 0) -> (2, 1) -> (3, 0) -> null
2328
+ *
2329
+ * code: a<LF><LF>
2330
+ * locations: (1, 0) -> (1, 1) -> (2, 0) -> (3, 0) -> null
2331
+ *
2332
+ * code: <LF>
2333
+ * locations: (1, 0) -> (2, 0) -> null
2334
+ *
2335
+ * code:
2336
+ * locations: (1, 0) -> null
2337
+ * @param {SourceCode} sourceCode The sourceCode
2338
+ * @param {{line: number, column: number}} location The location
2339
+ * @returns {{line: number, column: number} | null} Next location
2340
+ */
2341
+ getNextLocation(sourceCode, { line, column }) {
2342
+ if (column < sourceCode.lines[line - 1].length) {
2343
+ return {
2344
+ line,
2345
+ column: column + 1,
2346
+ };
2347
+ }
2348
+
2349
+ if (line < sourceCode.lines.length) {
2350
+ return {
2351
+ line: line + 1,
2352
+ column: 0,
2353
+ };
2354
+ }
2355
+
2356
+ return null;
2357
+ },
2358
+
2359
+ /**
2360
+ * Gets the parenthesized text of a node. This is similar to sourceCode.getText(node), but it also includes any parentheses
2361
+ * surrounding the node.
2362
+ * @param {SourceCode} sourceCode The source code object
2363
+ * @param {ASTNode} node An expression node
2364
+ * @returns {string} The text representing the node, with all surrounding parentheses included
2365
+ */
2366
+ getParenthesisedText(sourceCode, node) {
2367
+ let leftToken = sourceCode.getFirstToken(node);
2368
+ let rightToken = sourceCode.getLastToken(node);
2369
+
2370
+ while (
2371
+ sourceCode.getTokenBefore(leftToken) &&
2372
+ sourceCode.getTokenBefore(leftToken).type === "Punctuator" &&
2373
+ sourceCode.getTokenBefore(leftToken).value === "(" &&
2374
+ sourceCode.getTokenAfter(rightToken) &&
2375
+ sourceCode.getTokenAfter(rightToken).type === "Punctuator" &&
2376
+ sourceCode.getTokenAfter(rightToken).value === ")"
2377
+ ) {
2378
+ leftToken = sourceCode.getTokenBefore(leftToken);
2379
+ rightToken = sourceCode.getTokenAfter(rightToken);
2380
+ }
2381
+
2382
+ return sourceCode
2383
+ .getText()
2384
+ .slice(leftToken.range[0], rightToken.range[1]);
2385
+ },
2386
+
2387
+ /**
2388
+ * Determine if a node has a possibility to be an Error object
2389
+ * @param {ASTNode} node ASTNode to check
2390
+ * @returns {boolean} True if there is a chance it contains an Error obj
2391
+ */
2392
+ couldBeError(node) {
2393
+ switch (node.type) {
2394
+ case "Identifier":
2395
+ case "CallExpression":
2396
+ case "NewExpression":
2397
+ case "MemberExpression":
2398
+ case "TaggedTemplateExpression":
2399
+ case "YieldExpression":
2400
+ case "AwaitExpression":
2401
+ case "ChainExpression":
2402
+ return true; // possibly an error object.
2403
+
2404
+ case "AssignmentExpression":
2405
+ if (["=", "&&="].includes(node.operator)) {
2406
+ return module.exports.couldBeError(node.right);
2407
+ }
2408
+
2409
+ if (["||=", "??="].includes(node.operator)) {
2410
+ return (
2411
+ module.exports.couldBeError(node.left) ||
2412
+ module.exports.couldBeError(node.right)
2413
+ );
2414
+ }
2415
+
2416
+ /**
2417
+ * All other assignment operators are mathematical assignment operators (arithmetic or bitwise).
2418
+ * An assignment expression with a mathematical operator can either evaluate to a primitive value,
2419
+ * or throw, depending on the operands. Thus, it cannot evaluate to an `Error` object.
2420
+ */
2421
+ return false;
2422
+
2423
+ case "SequenceExpression": {
2424
+ const exprs = node.expressions;
2425
+
2426
+ return (
2427
+ exprs.length !== 0 &&
2428
+ module.exports.couldBeError(exprs.at(-1))
2429
+ );
2430
+ }
2431
+
2432
+ case "LogicalExpression":
2433
+ /*
2434
+ * If the && operator short-circuits, the left side was falsy and therefore not an error, and if it
2435
+ * doesn't short-circuit, it takes the value from the right side, so the right side must always be
2436
+ * a plausible error. A future improvement could verify that the left side could be truthy by
2437
+ * excluding falsy literals.
2438
+ */
2439
+ if (node.operator === "&&") {
2440
+ return module.exports.couldBeError(node.right);
2441
+ }
2442
+
2443
+ return (
2444
+ module.exports.couldBeError(node.left) ||
2445
+ module.exports.couldBeError(node.right)
2446
+ );
2447
+
2448
+ case "ConditionalExpression":
2449
+ return (
2450
+ module.exports.couldBeError(node.consequent) ||
2451
+ module.exports.couldBeError(node.alternate)
2452
+ );
2453
+
2454
+ default:
2455
+ return false;
2456
+ }
2457
+ },
2458
+
2459
+ /**
2460
+ * Check if a given node is a numeric literal or not.
2461
+ * @param {ASTNode} node The node to check.
2462
+ * @returns {boolean} `true` if the node is a number or bigint literal.
2463
+ */
2464
+ isNumericLiteral(node) {
2465
+ return (
2466
+ node.type === "Literal" &&
2467
+ (typeof node.value === "number" || Boolean(node.bigint))
2468
+ );
2469
+ },
2470
+
2471
+ /**
2472
+ * Determines whether two tokens can safely be placed next to each other without merging into a single token
2473
+ * @param {Token|string} leftValue The left token. If this is a string, it will be tokenized and the last token will be used.
2474
+ * @param {Token|string} rightValue The right token. If this is a string, it will be tokenized and the first token will be used.
2475
+ * @returns {boolean} If the tokens cannot be safely placed next to each other, returns `false`. If the tokens can be placed
2476
+ * next to each other, behavior is undefined (although it should return `true` in most cases).
2477
+ */
2478
+ canTokensBeAdjacent(leftValue, rightValue) {
2479
+ const espreeOptions = {
2480
+ ecmaVersion: espree.latestEcmaVersion,
2481
+ comment: true,
2482
+ range: true,
2483
+ };
2484
+
2485
+ let leftToken;
2486
+
2487
+ if (typeof leftValue === "string") {
2488
+ let tokens;
2489
+
2490
+ try {
2491
+ tokens = espree.tokenize(leftValue, espreeOptions);
2492
+ } catch {
2493
+ return false;
2494
+ }
2495
+
2496
+ const comments = tokens.comments;
2497
+
2498
+ leftToken = tokens.at(-1);
2499
+ if (comments.length) {
2500
+ const lastComment = comments.at(-1);
2501
+
2502
+ if (!leftToken || lastComment.range[0] > leftToken.range[0]) {
2503
+ leftToken = lastComment;
2504
+ }
2505
+ }
2506
+ } else {
2507
+ leftToken = leftValue;
2508
+ }
2509
+
2510
+ /*
2511
+ * If a hashbang comment was passed as a token object from SourceCode,
2512
+ * its type will be "Shebang" because of the way ESLint itself handles hashbangs.
2513
+ * If a hashbang comment was passed in a string and then tokenized in this function,
2514
+ * its type will be "Hashbang" because of the way Espree tokenizes hashbangs.
2515
+ */
2516
+ if (leftToken.type === "Shebang" || leftToken.type === "Hashbang") {
2517
+ return false;
2518
+ }
2519
+
2520
+ let rightToken;
2521
+
2522
+ if (typeof rightValue === "string") {
2523
+ let tokens;
2524
+
2525
+ try {
2526
+ tokens = espree.tokenize(rightValue, espreeOptions);
2527
+ } catch {
2528
+ return false;
2529
+ }
2530
+
2531
+ const comments = tokens.comments;
2532
+
2533
+ rightToken = tokens[0];
2534
+ if (comments.length) {
2535
+ const firstComment = comments[0];
2536
+
2537
+ if (
2538
+ !rightToken ||
2539
+ firstComment.range[0] < rightToken.range[0]
2540
+ ) {
2541
+ rightToken = firstComment;
2542
+ }
2543
+ }
2544
+ } else {
2545
+ rightToken = rightValue;
2546
+ }
2547
+
2548
+ if (
2549
+ leftToken.type === "Punctuator" ||
2550
+ rightToken.type === "Punctuator"
2551
+ ) {
2552
+ if (
2553
+ leftToken.type === "Punctuator" &&
2554
+ rightToken.type === "Punctuator"
2555
+ ) {
2556
+ const PLUS_TOKENS = new Set(["+", "++"]);
2557
+ const MINUS_TOKENS = new Set(["-", "--"]);
2558
+
2559
+ return !(
2560
+ (PLUS_TOKENS.has(leftToken.value) &&
2561
+ PLUS_TOKENS.has(rightToken.value)) ||
2562
+ (MINUS_TOKENS.has(leftToken.value) &&
2563
+ MINUS_TOKENS.has(rightToken.value))
2564
+ );
2565
+ }
2566
+ if (leftToken.type === "Punctuator" && leftToken.value === "/") {
2567
+ return !["Block", "Line", "RegularExpression"].includes(
2568
+ rightToken.type,
2569
+ );
2570
+ }
2571
+ return true;
2572
+ }
2573
+
2574
+ if (
2575
+ leftToken.type === "String" ||
2576
+ rightToken.type === "String" ||
2577
+ leftToken.type === "Template" ||
2578
+ rightToken.type === "Template"
2579
+ ) {
2580
+ return true;
2581
+ }
2582
+
2583
+ if (
2584
+ leftToken.type !== "Numeric" &&
2585
+ rightToken.type === "Numeric" &&
2586
+ rightToken.value.startsWith(".")
2587
+ ) {
2588
+ return true;
2589
+ }
2590
+
2591
+ if (
2592
+ leftToken.type === "Block" ||
2593
+ rightToken.type === "Block" ||
2594
+ rightToken.type === "Line"
2595
+ ) {
2596
+ return true;
2597
+ }
2598
+
2599
+ if (rightToken.type === "PrivateIdentifier") {
2600
+ return true;
2601
+ }
2602
+
2603
+ return false;
2604
+ },
2605
+
2606
+ /**
2607
+ * Get the `loc` object of a given name in a `/*globals` directive comment.
2608
+ * @param {SourceCode} sourceCode The source code to convert index to loc.
2609
+ * @param {Comment} comment The `/*globals` directive comment which include the name.
2610
+ * @param {string} name The name to find.
2611
+ * @returns {SourceLocation} The `loc` object.
2612
+ */
2613
+ getNameLocationInGlobalDirectiveComment(sourceCode, comment, name) {
2614
+ const namePattern = new RegExp(
2615
+ `[\\s,]${escapeRegExp(name)}(?:$|[\\s,:])`,
2616
+ "gu",
2617
+ );
2618
+
2619
+ // To ignore the first text "global".
2620
+ namePattern.lastIndex = comment.value.indexOf("global") + 6;
2621
+
2622
+ // Search a given variable name.
2623
+ const match = namePattern.exec(comment.value);
2624
+
2625
+ // Convert the index to loc.
2626
+ const start = sourceCode.getLocFromIndex(
2627
+ comment.range[0] + "/*".length + (match ? match.index + 1 : 0),
2628
+ );
2629
+ const end = {
2630
+ line: start.line,
2631
+ column: start.column + (match ? name.length : 1),
2632
+ };
2633
+
2634
+ return { start, end };
2635
+ },
2636
+
2637
+ /**
2638
+ * Determines whether the given raw string contains an octal escape sequence
2639
+ * or a non-octal decimal escape sequence ("\8", "\9").
2640
+ *
2641
+ * "\1", "\2" ... "\7", "\8", "\9"
2642
+ * "\00", "\01" ... "\07", "\08", "\09"
2643
+ *
2644
+ * "\0", when not followed by a digit, is not an octal escape sequence.
2645
+ * @param {string} rawString A string in its raw representation.
2646
+ * @returns {boolean} `true` if the string contains at least one octal escape sequence
2647
+ * or at least one non-octal decimal escape sequence.
2648
+ */
2649
+ hasOctalOrNonOctalDecimalEscapeSequence(rawString) {
2650
+ return OCTAL_OR_NON_OCTAL_DECIMAL_ESCAPE_PATTERN.test(rawString);
2651
+ },
2652
+
2653
+ /**
2654
+ * Determines whether the given node is a template literal without expressions.
2655
+ * @param {ASTNode} node Node to check.
2656
+ * @returns {boolean} True if the node is a template literal without expressions.
2657
+ */
2658
+ isStaticTemplateLiteral(node) {
2659
+ return node.type === "TemplateLiteral" && node.expressions.length === 0;
2660
+ },
2661
+
2662
+ /**
2663
+ * Determines whether the existing curly braces around the single statement are necessary to preserve the semantics of the code.
2664
+ * The braces, which make the given block body, are necessary in either of the following situations:
2665
+ *
2666
+ * 1. The statement is a lexical declaration.
2667
+ * 2. Without the braces, an `if` within the statement would become associated with an `else` after the closing brace:
2668
+ *
2669
+ * if (a) {
2670
+ * if (b)
2671
+ * foo();
2672
+ * }
2673
+ * else
2674
+ * bar();
2675
+ *
2676
+ * if (a)
2677
+ * while (b)
2678
+ * while (c) {
2679
+ * while (d)
2680
+ * if (e)
2681
+ * while(f)
2682
+ * foo();
2683
+ * }
2684
+ * else
2685
+ * bar();
2686
+ * @param {ASTNode} node `BlockStatement` body with exactly one statement directly inside. The statement can have its own nested statements.
2687
+ * @param {SourceCode} sourceCode The source code
2688
+ * @returns {boolean} `true` if the braces are necessary - removing them (replacing the given `BlockStatement` body with its single statement content)
2689
+ * would change the semantics of the code or produce a syntax error.
2690
+ */
2691
+ areBracesNecessary(node, sourceCode) {
2692
+ /**
2693
+ * Determines if the given node is a lexical declaration (let, const, using, await using, function, or class)
2694
+ * @param {ASTNode} nodeToCheck The node to check
2695
+ * @returns {boolean} True if the node is a lexical declaration
2696
+ * @private
2697
+ */
2698
+ function isLexicalDeclaration(nodeToCheck) {
2699
+ if (nodeToCheck.type === "VariableDeclaration") {
2700
+ return LEXICAL_DECLARATION_KINDS.has(nodeToCheck.kind);
2701
+ }
2702
+
2703
+ return (
2704
+ nodeToCheck.type === "FunctionDeclaration" ||
2705
+ nodeToCheck.type === "ClassDeclaration"
2706
+ );
2707
+ }
2708
+
2709
+ /**
2710
+ * Checks if the given token is an `else` token or not.
2711
+ * @param {Token} token The token to check.
2712
+ * @returns {boolean} `true` if the token is an `else` token.
2713
+ */
2714
+ function isElseKeywordToken(token) {
2715
+ return token.value === "else" && token.type === "Keyword";
2716
+ }
2717
+
2718
+ /**
2719
+ * Determines whether the given node has an `else` keyword token as the first token after.
2720
+ * @param {ASTNode} nodeToCheck The node to check.
2721
+ * @returns {boolean} `true` if the node is followed by an `else` keyword token.
2722
+ */
2723
+ function isFollowedByElseKeyword(nodeToCheck) {
2724
+ const nextToken = sourceCode.getTokenAfter(nodeToCheck);
2725
+
2726
+ return Boolean(nextToken) && isElseKeywordToken(nextToken);
2727
+ }
2728
+
2729
+ /**
2730
+ * Determines whether the code represented by the given node contains an `if` statement
2731
+ * that would become associated with an `else` keyword directly appended to that code.
2732
+ *
2733
+ * Examples where it returns `true`:
2734
+ *
2735
+ * if (a)
2736
+ * foo();
2737
+ *
2738
+ * if (a) {
2739
+ * foo();
2740
+ * }
2741
+ *
2742
+ * if (a)
2743
+ * foo();
2744
+ * else if (b)
2745
+ * bar();
2746
+ *
2747
+ * while (a)
2748
+ * if (b)
2749
+ * if(c)
2750
+ * foo();
2751
+ * else
2752
+ * bar();
2753
+ *
2754
+ * Examples where it returns `false`:
2755
+ *
2756
+ * if (a)
2757
+ * foo();
2758
+ * else
2759
+ * bar();
2760
+ *
2761
+ * while (a) {
2762
+ * if (b)
2763
+ * if(c)
2764
+ * foo();
2765
+ * else
2766
+ * bar();
2767
+ * }
2768
+ *
2769
+ * while (a)
2770
+ * if (b) {
2771
+ * if(c)
2772
+ * foo();
2773
+ * }
2774
+ * else
2775
+ * bar();
2776
+ * @param {ASTNode} nodeToCheck Node representing the code to check.
2777
+ * @returns {boolean} `true` if an `if` statement within the code would become associated with an `else` appended to that code.
2778
+ */
2779
+ function hasUnsafeIf(nodeToCheck) {
2780
+ switch (nodeToCheck.type) {
2781
+ case "IfStatement":
2782
+ if (!nodeToCheck.alternate) {
2783
+ return true;
2784
+ }
2785
+ return hasUnsafeIf(nodeToCheck.alternate);
2786
+ case "ForStatement":
2787
+ case "ForInStatement":
2788
+ case "ForOfStatement":
2789
+ case "LabeledStatement":
2790
+ case "WithStatement":
2791
+ case "WhileStatement":
2792
+ return hasUnsafeIf(nodeToCheck.body);
2793
+ default:
2794
+ return false;
2795
+ }
2796
+ }
2797
+
2798
+ const statement = node.body[0];
2799
+
2800
+ return (
2801
+ isLexicalDeclaration(statement) ||
2802
+ (hasUnsafeIf(statement) && isFollowedByElseKeyword(node))
2803
+ );
2804
+ },
2805
+
2806
+ isReferenceToGlobalVariable,
2807
+ isLogicalExpression,
2808
+ isCoalesceExpression,
2809
+ isMixedLogicalAndCoalesceExpressions,
2810
+ isNullLiteral,
2811
+ getStaticStringValue,
2812
+ getStaticPropertyName,
2813
+ skipChainExpression,
2814
+ isSpecificId,
2815
+ isSpecificMemberAccess,
2816
+ equalLiteralValue,
2817
+ isSameReference,
2818
+ isLogicalAssignmentOperator,
2819
+ getSwitchCaseColonToken,
2820
+ getModuleExportName,
2821
+ isConstant,
2822
+ isTopLevelExpressionStatement,
2823
+ isDirective,
2824
+ isStartOfExpressionStatement,
2825
+ needsPrecedingSemicolon,
2826
+ isImportAttributeKey,
2827
+ getOpeningParenOfParams,
2828
+ };