@boyingliu01/xp-gate 0.38.126 → 0.39.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (291) hide show
  1. package/README.md +93 -0
  2. package/adapters/gate-3.sh +13 -2
  3. package/adapters/python.sh +36 -38
  4. package/bin/xp-gate.js +11 -0
  5. package/build-integrity/gate-10-lines.ts +98 -0
  6. package/build-integrity/gate-10.ts +98 -109
  7. package/build-integrity/quote-masker.ts +17 -3
  8. package/gate-3.sh +13 -2
  9. package/gates/common-process.ts +116 -34
  10. package/gates/common.ts +51 -15
  11. package/gates/gate-3.ts +166 -61
  12. package/gates/gate-8.ts +76 -24
  13. package/gates/gate-9.ts +276 -82
  14. package/gates/pbt-detect.ts +70 -39
  15. package/gates/python-health.ts +236 -98
  16. package/gates/test-layers.ts +103 -30
  17. package/hooks/gate-3.sh +13 -2
  18. package/hooks/gate-entries/gate-1-entry.sh +10 -1
  19. package/hooks/gate-entries/gate-5-entry.sh +5 -1
  20. package/hooks/lib/validate-code-walkthrough.cjs +324 -99
  21. package/hooks/pre-commit +52 -0
  22. package/hooks/pre-push +54 -3
  23. package/lib/agent-runtime-journal.js +104 -37
  24. package/lib/arch.js +6 -0
  25. package/lib/baseline.js +329 -201
  26. package/lib/check.js +38 -2
  27. package/lib/doctor-constants.js +43 -0
  28. package/lib/doctor.js +2008 -1001
  29. package/lib/flaky.js +178 -79
  30. package/lib/gate-runner.js +110 -63
  31. package/lib/init.js +6 -0
  32. package/lib/language-capability-surfaces.js +5 -2
  33. package/lib/language-registry.js +608 -0
  34. package/lib/language-tools.js +487 -1018
  35. package/lib/phase-transition.js +646 -446
  36. package/lib/prepush-evidence.js +174 -0
  37. package/lib/sprint-audit.js +52 -22
  38. package/lib/sprint-discovery.js +66 -35
  39. package/lib/sprint-format.js +114 -0
  40. package/lib/sprint-init.js +372 -118
  41. package/lib/sprint-status.js +134 -90
  42. package/lib/star-notice.js +346 -0
  43. package/lib/tool-display.js +52 -0
  44. package/lib/tool-install.js +179 -0
  45. package/lib/uninstall.js +331 -188
  46. package/mock-policy/gate-m3.ts +74 -23
  47. package/mock-policy/mock-decision-engine.ts +21 -7
  48. package/mock-policy/scope-scanner.ts +128 -69
  49. package/mutation/detect-ai-test.ts +20 -12
  50. package/mutation/gate-m.ts +6 -2
  51. package/mutation/init-baseline.ts +49 -13
  52. package/mutation/runners/go-mutant-runner.ts +7 -49
  53. package/mutation/runners/gremlins-runner.ts +53 -18
  54. package/mutation/runners/mutmut-runner.ts +455 -163
  55. package/mutation/runners/pitest-runner.ts +85 -131
  56. package/mutation/runners/spawn-with-capture.ts +304 -0
  57. package/mutation/runners/stryker-runner.ts +14 -55
  58. package/mutation/update-baseline.ts +25 -18
  59. package/package.json +20 -8
  60. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  61. package/plugins/claude-code/bin/delphi-review-guard.sh +12 -61
  62. package/plugins/claude-code/skills/delphi-review/.delphi-config.json.example +6 -11
  63. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  64. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  65. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  66. package/plugins/dsh/package.json +1 -1
  67. package/plugins/dsh/scripts/prepack.cjs +43 -18
  68. package/plugins/dsh/scripts/verify-skill-provider.mjs +39 -14
  69. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +6 -11
  70. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  71. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  72. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  73. package/plugins/opencode/index.ts +337 -123
  74. package/plugins/opencode/package.json +1 -1
  75. package/plugins/opencode/scripts/prepack.cjs +41 -16
  76. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +6 -11
  77. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  78. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  79. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  80. package/plugins/qoder/bin/sprint-flow-guard.sh +12 -60
  81. package/plugins/qoder/plugin.json +1 -1
  82. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +6 -11
  83. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  84. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  85. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  86. package/plugins/shared/README.md +3 -0
  87. package/plugins/shared/bin/delphi-review-guard.sh +68 -0
  88. package/principles/adapters/control-nesting.ts +481 -168
  89. package/principles/adapters/cpp.ts +61 -22
  90. package/principles/adapters/csharp.ts +183 -66
  91. package/principles/adapters/dart.ts +11 -1
  92. package/principles/adapters/duplication.ts +49 -16
  93. package/principles/adapters/import-clause.ts +62 -15
  94. package/principles/adapters/java.ts +199 -70
  95. package/principles/adapters/line-comment.ts +18 -0
  96. package/principles/adapters/member-scan.ts +50 -8
  97. package/principles/adapters/php.ts +232 -103
  98. package/principles/adapters/python.ts +25 -18
  99. package/principles/adapters/quote-state.ts +21 -8
  100. package/principles/adapters/typescript-mask.ts +276 -0
  101. package/principles/adapters/typescript.ts +206 -200
  102. package/principles/analyzer.ts +16 -6
  103. package/principles/baseline-prune.ts +18 -8
  104. package/principles/baseline.ts +28 -11
  105. package/principles/boy-scout-usage.ts +26 -0
  106. package/principles/boy-scout.ts +261 -180
  107. package/principles/config.ts +183 -57
  108. package/principles/direct-execution.ts +24 -12
  109. package/principles/lint-baseline.ts +235 -122
  110. package/principles/rules/arch/dependency.ts +34 -25
  111. package/principles/rules/arch/shared.ts +24 -20
  112. package/principles/rules/clean-code/deep-nesting.ts +23 -13
  113. package/principles/rules/clean-code/god-class.ts +67 -41
  114. package/principles/rules/clean-code/large-file.ts +30 -23
  115. package/principles/rules/clean-code/long-function.ts +51 -37
  116. package/principles/rules/clean-code/magic-numbers.ts +51 -36
  117. package/principles/rules/clean-code/many-exports.ts +46 -29
  118. package/principles/rules/clean-code/missing-error-handling.ts +38 -20
  119. package/principles/rules/clean-code/too-many-params.ts +41 -22
  120. package/principles/rules/function-source.ts +62 -0
  121. package/principles/rules/solid/dip.ts +10 -6
  122. package/principles/rules/solid/isp.ts +64 -24
  123. package/principles/rules/solid/lsp.ts +66 -18
  124. package/principles/rules/solid/ocp.ts +29 -13
  125. package/principles/rules/solid/srp.ts +34 -18
  126. package/principles/warnings-count.ts +43 -0
  127. package/scripts/__tests__/prepush-source-classification.test.js +129 -0
  128. package/scripts/delphi-config-read.cjs +245 -0
  129. package/scripts/delphi-external-review.cjs +410 -585
  130. package/scripts/delphi-json-extract.cjs +108 -0
  131. package/scripts/delphi-model-validation.cjs +297 -0
  132. package/scripts/delphi-prompts.cjs +55 -0
  133. package/scripts/delphi-repo-tools.cjs +273 -0
  134. package/scripts/delphi-seat-calibration.cjs +204 -0
  135. package/scripts/run-bats-ci.cjs +240 -97
  136. package/scripts/sync-package-content.js +18 -2
  137. package/skills/delphi-review/.delphi-config.json.example +6 -11
  138. package/skills/delphi-review/AGENTS.md +1 -1
  139. package/skills/sprint-flow/AGENTS.md +1 -1
  140. package/skills/test-specification-alignment/AGENTS.md +1 -1
  141. package/lib/__tests__/agent-runtime-journal.test.js +0 -326
  142. package/lib/__tests__/arch-config-template.test.js +0 -190
  143. package/lib/__tests__/arch.test.js +0 -430
  144. package/lib/__tests__/assertion-debt.test.js +0 -99
  145. package/lib/__tests__/audit-cli-contract.test.ts +0 -117
  146. package/lib/__tests__/audit-log.test.ts +0 -107
  147. package/lib/__tests__/audit-skip-reasons.test.ts +0 -143
  148. package/lib/__tests__/baseline-completeness.test.js +0 -264
  149. package/lib/__tests__/baseline-shell-scope.test.js +0 -60
  150. package/lib/__tests__/baseline-unevaluated.test.js +0 -142
  151. package/lib/__tests__/baseline.test.js +0 -212
  152. package/lib/__tests__/bootstrap.test.js +0 -60
  153. package/lib/__tests__/check-alignment-cli.test.mjs +0 -94
  154. package/lib/__tests__/check-alignment-reasons.test.mjs +0 -101
  155. package/lib/__tests__/check-all-skip-accounting.test.js +0 -171
  156. package/lib/__tests__/check-changed-brief.test.js +0 -63
  157. package/lib/__tests__/check-normalize-exit.test.js +0 -24
  158. package/lib/__tests__/check-single-file.test.js +0 -114
  159. package/lib/__tests__/check-tools-list.test.js +0 -155
  160. package/lib/__tests__/check-version.test.js +0 -463
  161. package/lib/__tests__/coverage-scope.test.js +0 -140
  162. package/lib/__tests__/coverage-threshold.test.js +0 -80
  163. package/lib/__tests__/crap-cli.test.js +0 -87
  164. package/lib/__tests__/crap.test.js +0 -494
  165. package/lib/__tests__/debt-classify.test.js +0 -78
  166. package/lib/__tests__/delphi-channel-doctor.test.js +0 -116
  167. package/lib/__tests__/delphi-channel-uninstall.test.js +0 -128
  168. package/lib/__tests__/delphi-channel.test.js +0 -109
  169. package/lib/__tests__/delphi-setup.test.js +0 -203
  170. package/lib/__tests__/deploy-manifest-check-wired.test.js +0 -138
  171. package/lib/__tests__/deploy-manifest-completeness.test.js +0 -151
  172. package/lib/__tests__/deploy-manifest-consumers-adapter-uninstall.test.js +0 -40
  173. package/lib/__tests__/deploy-manifest-consumers-no-private-lists.test.js +0 -74
  174. package/lib/__tests__/deploy-manifest-projection.test.js +0 -66
  175. package/lib/__tests__/deploy-manifest-shell-parity.test.js +0 -108
  176. package/lib/__tests__/deploy-manifest.test.js +0 -97
  177. package/lib/__tests__/detect-deps-dsh-profile.test.js +0 -323
  178. package/lib/__tests__/detect-deps-gate-identity.test.js +0 -135
  179. package/lib/__tests__/detect-deps.test.js +0 -655
  180. package/lib/__tests__/doctor-469-hook-env.test.js +0 -211
  181. package/lib/__tests__/doctor-arch-tools.test.js +0 -169
  182. package/lib/__tests__/doctor-audit-ledger.test.js +0 -61
  183. package/lib/__tests__/doctor-brief.test.js +0 -59
  184. package/lib/__tests__/doctor-delphi.test.js +0 -628
  185. package/lib/__tests__/doctor-drift-direction.test.js +0 -104
  186. package/lib/__tests__/doctor-drift-round2.test.js +0 -215
  187. package/lib/__tests__/doctor-exec-retry.test.js +0 -162
  188. package/lib/__tests__/doctor-executed-surface.test.js +0 -230
  189. package/lib/__tests__/doctor-helpers.test.js +0 -139
  190. package/lib/__tests__/doctor-hook-drift.test.js +0 -329
  191. package/lib/__tests__/doctor-hook-signatures.test.js +0 -65
  192. package/lib/__tests__/doctor-machine-mutation.test.js +0 -116
  193. package/lib/__tests__/doctor-module-drift.test.js +0 -212
  194. package/lib/__tests__/doctor-module-resolution-parity.test.js +0 -463
  195. package/lib/__tests__/doctor-path-equivalence.test.js +0 -70
  196. package/lib/__tests__/doctor-repair-boundary.test.js +0 -52
  197. package/lib/__tests__/doctor-signature-stability.test.js +0 -55
  198. package/lib/__tests__/doctor-spawn-capability.test.js +0 -116
  199. package/lib/__tests__/doctor-timeout-partial.test.js +0 -79
  200. package/lib/__tests__/doctor-tool-delegation.test.js +0 -156
  201. package/lib/__tests__/doctor-tui-skill-freshness.test.js +0 -385
  202. package/lib/__tests__/doctor.test.js +0 -1320
  203. package/lib/__tests__/find-bash-wsl.test.js +0 -121
  204. package/lib/__tests__/flaky.test.js +0 -128
  205. package/lib/__tests__/foreign-hooks-global.test.js +0 -125
  206. package/lib/__tests__/gate-audit-skip.test.ts +0 -81
  207. package/lib/__tests__/gate-audit.test.ts +0 -440
  208. package/lib/__tests__/gate-coverage-hook-floor.test.js +0 -94
  209. package/lib/__tests__/gate-coverage.test.js +0 -204
  210. package/lib/__tests__/gate-entry-provenance.test.js +0 -71
  211. package/lib/__tests__/gate-numbering.test.js +0 -79
  212. package/lib/__tests__/gate-rules.test.js +0 -58
  213. package/lib/__tests__/gate-runner-tsx-invocation.test.js +0 -149
  214. package/lib/__tests__/gate-runner-verdict.test.js +0 -105
  215. package/lib/__tests__/gate-runner.test.js +0 -371
  216. package/lib/__tests__/gate2-verdict.test.js +0 -183
  217. package/lib/__tests__/helpers/lib-sandbox.cjs +0 -55
  218. package/lib/__tests__/hook-health-path.test.js +0 -109
  219. package/lib/__tests__/hook-health.test.js +0 -85
  220. package/lib/__tests__/init-gitignore.test.js +0 -204
  221. package/lib/__tests__/init-gitleaks-notice.test.js +0 -57
  222. package/lib/__tests__/init.test.js +0 -530
  223. package/lib/__tests__/install-cmd.test.js +0 -6
  224. package/lib/__tests__/install-sh-deploy-manifest.test.js +0 -80
  225. package/lib/__tests__/install-skill-full-dir.test.js +0 -194
  226. package/lib/__tests__/install-skill.test.js +0 -416
  227. package/lib/__tests__/install-tools-repair.test.js +0 -263
  228. package/lib/__tests__/issue-519-phase-transition-guard.test.js +0 -233
  229. package/lib/__tests__/issue-566-sync-hooks-backup.test.js +0 -228
  230. package/lib/__tests__/issue-583-hook-deploy-log.test.js +0 -121
  231. package/lib/__tests__/issue-586-principles-cmdline.test.js +0 -218
  232. package/lib/__tests__/issue-589-check-all-gate3.test.js +0 -190
  233. package/lib/__tests__/issue-590-archlint-vacuous-pass.test.js +0 -138
  234. package/lib/__tests__/issue-618-gate-not-run.test.js +0 -100
  235. package/lib/__tests__/jscpd-entry-resolution.test.js +0 -143
  236. package/lib/__tests__/language-capability.test.js +0 -318
  237. package/lib/__tests__/language-tools-build-file-install.test.js +0 -82
  238. package/lib/__tests__/language-tools-detect.test.js +0 -301
  239. package/lib/__tests__/migrate.test.js +0 -232
  240. package/lib/__tests__/mirror-manifest.test.js +0 -64
  241. package/lib/__tests__/mirror-sync.test.js +0 -803
  242. package/lib/__tests__/next-sprint.test.js +0 -231
  243. package/lib/__tests__/npm-package.test.js +0 -140
  244. package/lib/__tests__/phase-transition.test.js +0 -1136
  245. package/lib/__tests__/principles-csharp-coverage.test.js +0 -227
  246. package/lib/__tests__/principles-directory.test.js +0 -87
  247. package/lib/__tests__/qoder-delphi-agents.test.js +0 -316
  248. package/lib/__tests__/retro-gate-m.test.js +0 -144
  249. package/lib/__tests__/retro.test.js +0 -131
  250. package/lib/__tests__/rework.test.js +0 -127
  251. package/lib/__tests__/rollback.test.js +0 -183
  252. package/lib/__tests__/runtime-journal.test.js +0 -164
  253. package/lib/__tests__/sastd-client.test.js +0 -514
  254. package/lib/__tests__/shared-paths-lazy-home.test.js +0 -67
  255. package/lib/__tests__/shared-paths.test.js +0 -130
  256. package/lib/__tests__/shared-utils-copyHooks-manifest.test.js +0 -69
  257. package/lib/__tests__/shared-utils.test.js +0 -180
  258. package/lib/__tests__/skill-flags.test.js +0 -48
  259. package/lib/__tests__/slo.test.js +0 -89
  260. package/lib/__tests__/sprint-audit.test.js +0 -207
  261. package/lib/__tests__/sprint-discovery.test.ts +0 -366
  262. package/lib/__tests__/sprint-state-manager.test.js +0 -310
  263. package/lib/__tests__/sprint-status-rework-704.test.js +0 -149
  264. package/lib/__tests__/sprint-status-rework.test.js +0 -329
  265. package/lib/__tests__/sprint-status.test.js +0 -193
  266. package/lib/__tests__/sprint-status.test.ts +0 -213
  267. package/lib/__tests__/test-alignment-java-702.test.ts +0 -177
  268. package/lib/__tests__/test-alignment-range-guard.test.ts +0 -82
  269. package/lib/__tests__/test-alignment.test.ts +0 -853
  270. package/lib/__tests__/tool-audit-collect.test.js +0 -184
  271. package/lib/__tests__/tool-audit-fixtures.js +0 -87
  272. package/lib/__tests__/tool-audit-latest.test.js +0 -84
  273. package/lib/__tests__/tool-audit.test.js +0 -428
  274. package/lib/__tests__/tsconfig.json +0 -8
  275. package/lib/__tests__/tsx-resolution.test.js +0 -89
  276. package/lib/__tests__/ui-detector.test.ts +0 -459
  277. package/lib/__tests__/ui-review.test.ts +0 -132
  278. package/lib/__tests__/uninstall-global-residue.test.js +0 -545
  279. package/lib/__tests__/uninstall-skill.test.js +0 -189
  280. package/lib/__tests__/uninstall.test.js +0 -717
  281. package/lib/__tests__/update-hooks.test.js +0 -737
  282. package/lib/__tests__/update-skill-flags.test.js +0 -78
  283. package/lib/__tests__/update-skill.test.js +0 -644
  284. package/lib/__tests__/upgrade-exec.test.js +0 -273
  285. package/lib/__tests__/upgrade-skill-sync.test.js +0 -65
  286. package/lib/__tests__/upgrade.test.js +0 -78
  287. package/lib/__tests__/windows-bash-probe.test.js +0 -123
  288. package/lib/check-alignment-runner.cjs +0 -97
  289. package/lib/coverage-total.sh +0 -92
  290. package/lib/layer-baseline.cjs +0 -94
  291. package/lib/mattpocock-license-verdict.json +0 -7
@@ -123,47 +123,74 @@ function nestingOfRange(body: string, from: number, to: number, depth: number):
123
123
  * level deeper), a nested function (whose body belongs to that function's own
124
124
  * score), or an ordinary token. Each returns where the scan resumes.
125
125
  */
126
+ /**
127
+ * Skip an anonymous arrow whose parameters are parenthesised: `items.map((x) => {`.
128
+ *
129
+ * The scan reaches `(` before any word, so this has to be checked here rather than in
130
+ * `isNestedFunctionIntro`. Without it the parenthesised form is charged to the
131
+ * enclosing function while `x => {` is not -- the same construct scored two different
132
+ * ways (#749 walkthrough).
133
+ *
134
+ * @returns the index to resume from, or -1 when this is not such an arrow
135
+ */
136
+ function consumeParenArrow(body: string, i: number, to: number): number {
137
+ if (body[i] !== '(') return -1;
138
+ const close = skipBalancedParen(body, i);
139
+ // A return-type annotation may sit between the parameter list and `=>`
140
+ // (`items.map((x): { ok: boolean } => { ... })`). Skipping past it keeps the arrow
141
+ // recognised, so its body is not charged to the enclosing function.
142
+ const afterParams = skipArrowReturnType(body, close, to);
143
+ if (!body.startsWith('=>', afterParams)) return -1;
144
+ const brace = findFunctionBodyBrace(body, afterParams, to);
145
+ return brace < 0 ? afterParams : skipBalancedBrace(body, brace);
146
+ }
147
+
148
+ /**
149
+ * Whether this word opens a control structure, rather than merely reading like one.
150
+ *
151
+ * A member access (`obj.if`) and a key or label (`{ if: ... }`) are not nesting, and
152
+ * saying so once keeps every caller from re-deriving it.
153
+ */
154
+ function isNestingKeywordAt(body: string, word: { word: string; end: number }, i: number): boolean {
155
+ if (!NESTING_KEYWORDS.has(word.word)) return false;
156
+ return !isMemberAccess(body, i) && !isKeyOrLabel(body, word.end);
157
+ }
158
+
159
+ /**
160
+ * Skip a nested function's body, or just its intro when it has none.
161
+ *
162
+ * A nested function -- named or anonymous -- owns the structures in its own body: the
163
+ * adapter already reports it as its own function, scored there. Skipping it keeps this
164
+ * function's score from being charged for nesting a reader never sees at this level,
165
+ * and matches lizard's `-ENS`.
166
+ *
167
+ * An expression-bodied arrow (`const f = () => 1;`) has no body to skip, so only the
168
+ * intro is dropped -- skipping a range would swallow the rest of the function.
169
+ *
170
+ * @param from the end of the function's name or parameter list
171
+ */
172
+ function skipNestedFunction(body: string, from: number, to: number): number {
173
+ const brace = findFunctionBodyBrace(body, from, to);
174
+ return brace < 0 ? from : skipBalancedBrace(body, brace);
175
+ }
176
+
126
177
  function consumeStructure(
127
178
  body: string, i: number, to: number, depth: number, setMax: (v: number) => void,
128
179
  ): number {
129
- // Anonymous arrow with a parenthesized parameter list: `items.map((x) => {`.
130
- // The scan reaches `(` before any word, so this has to be checked here rather
131
- // than in isNestedFunctionIntro. Without it the parenthesized form is charged
132
- // to the enclosing function while `x => {` is not -- the same construct scored
133
- // two different ways (#749 walkthrough).
134
- if (body[i] === '(') {
135
- const close = skipBalancedParen(body, i);
136
- // A return-type annotation may sit between the parameter list and `=>`
137
- // (`items.map((x): { ok: boolean } => { ... })`). Skip past it so the arrow
138
- // is still recognized and its body is not charged to the enclosing function.
139
- const afterParams = skipArrowReturnType(body, close, to);
140
- if (body.startsWith('=>', afterParams)) {
141
- const brace = findFunctionBodyBrace(body, afterParams, to);
142
- return brace < 0 ? afterParams : skipBalancedBrace(body, brace);
143
- }
144
- }
180
+ const arrowEnd = consumeParenArrow(body, i, to);
181
+ if (arrowEnd >= 0) return arrowEnd;
182
+
145
183
  const word = readWord(body, i);
146
184
  if (!word) return i + 1;
147
- if (NESTING_KEYWORDS.has(word.word) && !isMemberAccess(body, i) && !isKeyOrLabel(body, word.end)) {
148
- // A control structure owns a nested region: count whatever nests inside it
149
- // one level deeper, then resume past that region so its braces cannot be
150
- // mistaken for the enclosing level's.
185
+ if (isNestingKeywordAt(body, word, i)) {
186
+ // A control structure owns a nested region: count whatever nests inside it one
187
+ // level deeper, then resume past that region so its braces cannot be mistaken for
188
+ // the enclosing level's.
151
189
  const scope = locateControlBody(body, word.end, to);
152
190
  setMax(nestingOfRange(body, scope.bodyStart, scope.bodyEnd, depth + 1));
153
191
  return scope.bodyEnd;
154
192
  }
155
- if (isNestedFunctionIntro(body, i, word.end)) {
156
- // A nested function -- named or anonymous -- owns the structures in its own
157
- // body: the adapter already reports it as its own function, scored there.
158
- // Skipping it here keeps this function's score from being charged for
159
- // nesting a reader never sees at this level, and matches lizard's `-ENS`,
160
- // which attributes a callback's nesting to the callback.
161
- const brace = findFunctionBodyBrace(body, word.end, to);
162
- // Expression-bodied (`const f = () => 1;`): no body to skip, so drop only
163
- // the intro. Skipping a range here would swallow the rest of the function.
164
- if (brace < 0) return word.end;
165
- return skipBalancedBrace(body, brace);
166
- }
193
+ if (isNestedFunctionIntro(body, i, word.end)) return skipNestedFunction(body, word.end, to);
167
194
  return word.end;
168
195
  }
169
196
 
@@ -180,57 +207,118 @@ function consumeStructure(
180
207
  * @returns the half-open range to scan at the deeper level.
181
208
  */
182
209
  function locateControlBody(body: string, from: number, to: number): { bodyStart: number; bodyEnd: number } {
210
+ const start = skipControlHeader(body, from, to);
211
+ const braced = bracedBody(body, start);
212
+ return braced || bareBody(body, start, to);
213
+ }
214
+
215
+ /**
216
+ * Step past the modifier and condition list: optional `await`, then `(...)`.
217
+ *
218
+ * `for await (...)` puts the modifier between the keyword and the condition. Without
219
+ * skipping it the loop body looked brace-less and was cut at the newline, losing a
220
+ * level.
221
+ *
222
+ * @returns the index of the first character after the header
223
+ */
224
+ function skipControlHeader(body: string, from: number, to: number): number {
183
225
  let i = skipSpaces(body, from, to);
184
- // `for await (...)` puts the `await` modifier between the keyword and the
185
- // condition. Without skipping it the loop body looked brace-less and was cut
186
- // at the newline, losing a level.
187
226
  if (body.startsWith('await', i) && !/[\w$]/.test(body[i + 5] ?? '')) {
188
227
  i = skipSpaces(body, i + 5, to);
189
228
  }
190
- if (body[i] === '(') {
191
- let parens = 0;
192
- for (; i < to; i++) {
193
- if (body[i] === '(') parens++;
194
- else if (body[i] === ')') {
195
- parens--;
196
- if (parens === 0) { i++; break; }
197
- }
198
- }
199
- i = skipSpaces(body, i, to);
200
- }
201
- if (body[i] === '{') {
202
- return { bodyStart: i + 1, bodyEnd: skipBalancedBrace(body, i) - 1 };
203
- }
204
- // Brace-less body. When the body is itself a control structure, the region to
205
- // scan starts at that structure's keyword and ends where its own body ends --
206
- // each level then adds its own +1 as the scan descends, so `if (a)\n if (b)\n
207
- // if (c) { }` nests three deep. Returning the innermost range directly would
208
- // skip the intermediate levels. A trailing `else` belongs to that inner `if`
209
- // (`if (a) if (b) { } else { }`), so it is included or the `else` body would be
210
- // rescanned at the outer depth.
211
- const head = readWord(body, i);
212
- if (head && NESTING_KEYWORDS.has(head.word) && !isMemberAccess(body, i) && !isKeyOrLabel(body, head.end)) {
213
- const inner = locateControlBody(body, head.end, to);
214
- // `inner.bodyEnd` is inclusive of the closing `}`, so step past it before
215
- // looking for a trailing `else`/`catch`/`finally`.
216
- let afterInner = inner.bodyEnd;
217
- if (body[afterInner] === '}') afterInner++;
218
- afterInner = skipSpaces(body, afterInner, to);
219
- const tail = readWord(body, afterInner);
220
- if (tail && (tail.word === 'else' || tail.word === 'catch' || tail.word === 'finally')) {
221
- return { bodyStart: i, bodyEnd: locateControlBody(body, tail.end, to).bodyEnd };
222
- }
223
- return { bodyStart: i, bodyEnd: inner.bodyEnd };
224
- }
225
- // Otherwise it ends at the statement end, which for JavaScript is a newline as
226
- // much as a `;`. Stopping only at `;` would swallow every following statement
227
- // and score sequential guard clauses as nesting.
228
- let end = i;
229
- while (end < to && body[end] !== ';' && body[end] !== '\n') end++;
230
- if (end < to && body[end] === ';') end++;
231
- return { bodyStart: i, bodyEnd: end };
229
+ if (body[i] !== '(') return i;
230
+ return skipSpaces(body, skipBalancedParen(body, i), to);
231
+ }
232
+
233
+ /**
234
+ * The region inside a `{ ... }` body, or null when the body is brace-less.
235
+ */
236
+ function bracedBody(body: string, start: number): { bodyStart: number; bodyEnd: number } | null {
237
+ if (body[start] !== '{') return null;
238
+ return { bodyStart: start + 1, bodyEnd: skipBalancedBrace(body, start) - 1 };
232
239
  }
233
240
 
241
+ /**
242
+ * The region of a brace-less body.
243
+ *
244
+ * When the body is itself a control structure, the region starts at that structure's
245
+ * keyword and ends where its own body ends -- each level adds its own +1 as the scan
246
+ * descends, so three nested single-statement `if`s nest three deep. Returning the
247
+ * innermost range directly would skip the intermediate levels.
248
+ */
249
+ function bareBody(body: string, start: number, to: number): { bodyStart: number; bodyEnd: number } {
250
+ return nestedControlBody(body, start, to) || statementBody(body, start, to);
251
+ }
252
+
253
+ /**
254
+ * A nested control structure as the body, or null when this is not one.
255
+ *
256
+ * A trailing `else` belongs to the inner structure (`if (a) if (b) { } else { }`), so
257
+ * it is included -- otherwise the `else` body would be rescanned at the outer depth.
258
+ */
259
+ function nestedControlBody(body: string, start: number, to: number): { bodyStart: number; bodyEnd: number } | null {
260
+ const head = readWord(body, start);
261
+ if (!head || !isNestingHead(body, head, start)) return null;
262
+
263
+ const inner = locateControlBody(body, head.end, to);
264
+ const tail = trailingClause(body, inner.bodyEnd, to);
265
+ if (!tail) return { bodyStart: start, bodyEnd: inner.bodyEnd };
266
+ return { bodyStart: start, bodyEnd: locateControlBody(body, tail.end, to).bodyEnd };
267
+ }
268
+
269
+ /**
270
+ * A statement body: ends at a semicolon or a newline, both of which terminate a
271
+ * JavaScript statement here. Stopping only at the semicolon would swallow every
272
+ * following statement and score sequential guard clauses as nesting.
273
+ */
274
+ function statementBody(body: string, start: number, to: number): { bodyStart: number; bodyEnd: number } {
275
+ const end = skipToStatementEnd(body, start, to);
276
+ return { bodyStart: start, bodyEnd: end };
277
+ }
278
+
279
+ /** Whether this character ends a bare statement body. */
280
+ function endsStatement(c: string): boolean {
281
+ return c === ';' || c === '\n';
282
+ }
283
+
284
+ /**
285
+ * The index just past a brace-less body's statement.
286
+ *
287
+ * The `;` is CONSUMED but the newline is not: an ASI-terminated statement ends before
288
+ * the line break, and consuming the break would join it to the next statement.
289
+ */
290
+ function skipToStatementEnd(body: string, start: number, to: number): number {
291
+ let end = start;
292
+ while (end < to && !endsStatement(body[end])) end++;
293
+ return end < to && body[end] === ';' ? end + 1 : end;
294
+ }
295
+
296
+ /**
297
+ * Whether this word opens a nested control structure worth descending into.
298
+ *
299
+ * A member access and a key or label read as keywords but are not nesting.
300
+ */
301
+ function isNestingHead(body: string, head: { word: string; end: number }, at: number): boolean {
302
+ if (!NESTING_KEYWORDS.has(head.word)) return false;
303
+ return !isMemberAccess(body, at) && !isKeyOrLabel(body, head.end);
304
+ }
305
+
306
+ /**
307
+ * The `else` / `catch` / `finally` following a body, if any.
308
+ *
309
+ * The body end is inclusive of the closing brace, so the scan steps past it first.
310
+ */
311
+ function trailingClause(body: string, after: number, to: number): { word: string; end: number } | null {
312
+ let i = after;
313
+ if (body[i] === '}') i++;
314
+ i = skipSpaces(body, i, to);
315
+ const tail = readWord(body, i);
316
+ return tail && CONTINUATION_KEYWORDS.has(tail.word) ? tail : null;
317
+ }
318
+
319
+ /** Keywords that CONTINUE a control structure past a closing brace. */
320
+ const CONTINUATION_KEYWORDS = new Set(['else', 'catch', 'finally']);
321
+
234
322
  /**
235
323
  * True when the parameter list starting at `open` is followed by a method body
236
324
  * or return-type annotation -- i.e. method shorthand rather than a call.
@@ -271,38 +359,77 @@ function isNestedFunctionIntro(body: string, wordStart: number, wordEnd: number)
271
359
  if (body.startsWith('=>', afterWord)) return true;
272
360
  // Method shorthand: `{ m() { } }`, `m(): void { }`, `m<T>() { }`. lizard -ENS
273
361
  // reports the method as its own function and the enclosing body as 0.
274
- if (body[afterWord] === '(' && isMethodSignature(body, afterWord)) return true;
275
- if (body[afterWord] === '<') {
276
- const afterGeneric = skipSpaces(body, skipBalancedAngle(body, afterWord), body.length);
277
- if (body[afterGeneric] === '(' && isMethodSignature(body, afterGeneric)) return true;
278
- }
362
+ if (isMethodShorthandAt(body, afterWord)) return true;
279
363
  return isAssignedFunctionIntro(body, current, wordEnd);
280
364
  }
281
365
 
366
+ /**
367
+ * Whether a method shorthand starts at `from`: `{ m() { } }`, `m(): void { }`,
368
+ * `m<T>() { }`.
369
+ *
370
+ * The generic form needs the angle list skipped first, or `<T>` reads as a comparison
371
+ * and the method goes unrecognised -- then lizard `-ENS` reports the method as its own
372
+ * function while this scan charges its body to the enclosing one.
373
+ */
374
+ function isMethodShorthandAt(body: string, from: number): boolean {
375
+ if (body[from] === '(') return isMethodSignature(body, from);
376
+ if (body[from] !== '<') return false;
377
+ const afterGeneric = skipSpaces(body, skipBalancedAngle(body, from), body.length);
378
+ return body[afterGeneric] === '(' && isMethodSignature(body, afterGeneric);
379
+ }
380
+
282
381
  /**
283
382
  * True for `const name = (...) => {` / `let name = function (...) {` /
284
383
  * `x = async () => {`, where the value assigned at `wordEnd` is a function.
285
384
  */
286
385
  function isAssignedFunctionIntro(body: string, current: string, wordEnd: number): boolean {
386
+ const rhs = indexOfAssignedValue(body, current, wordEnd);
387
+ if (rhs < 0) return false;
388
+ const start = skipAsyncModifier(body, rhs);
389
+ if (body.startsWith('function', start)) return true;
390
+ if (body[start] !== '(') return false;
391
+ const close = skipBalancedParen(body, start);
392
+ return body.startsWith('=>', skipArrowReturnType(body, close, body.length));
393
+ }
394
+
395
+ /**
396
+ * Where the value assigned by `current` starts, or -1 when this is not an assignment.
397
+ *
398
+ * `current` is either a DECLARATION keyword, where the value follows a name
399
+ * (`const name = ...`), or an identifier being assigned directly (`name = ...`).
400
+ */
401
+ function indexOfAssignedValue(body: string, current: string, wordEnd: number): number {
287
402
  let k = wordEnd;
288
- if (current === 'const' || current === 'let' || current === 'var') {
403
+ if (isDeclarationKeyword(current)) {
289
404
  const name = readWord(body, skipSpaces(body, k, body.length));
290
- if (!name) return false;
405
+ if (!name) return -1;
291
406
  k = name.end;
292
- } else if (!/^[A-Za-z_$][\w$]*$/.test(current)) {
293
- return false;
407
+ } else if (!IDENTIFIER.test(current)) {
408
+ return -1;
294
409
  }
295
410
  k = skipSpaces(body, k, body.length);
296
- if (body[k] !== '=') return false;
297
- k = skipSpaces(body, k + 1, body.length);
298
- // `const name = async (...) => {` -- the async modifier precedes the params.
299
- if (body.startsWith('async', k) && !/[\w$]/.test(body[k + 5] ?? '')) {
300
- k = skipSpaces(body, k + 5, body.length);
301
- }
302
- if (body.startsWith('function', k)) return true;
303
- if (body[k] !== '(') return false;
304
- const close = skipBalancedParen(body, k);
305
- return body.startsWith('=>', skipArrowReturnType(body, close, body.length));
411
+ if (body[k] !== '=') return -1;
412
+ return skipSpaces(body, k + 1, body.length);
413
+ }
414
+
415
+ /** A JavaScript identifier: what a bare assignment target must be. */
416
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
417
+
418
+ /** `const` / `let` / `var`: the value sits after a name. */
419
+ function isDeclarationKeyword(word: string): boolean {
420
+ return word === 'const' || word === 'let' || word === 'var';
421
+ }
422
+
423
+ /**
424
+ * Step past an `async` modifier, when there is one.
425
+ *
426
+ * `const name = async (...) => {` is an arrow too, and the modifier sits between the
427
+ * `=` and the parameter list.
428
+ */
429
+ function skipAsyncModifier(body: string, from: number): number {
430
+ if (!body.startsWith('async', from)) return from;
431
+ if (/[\w$]/.test(body[from + 5] ?? '')) return from;
432
+ return skipSpaces(body, from + 5, body.length);
306
433
  }
307
434
 
308
435
  /**
@@ -321,25 +448,46 @@ function isAssignedFunctionIntro(body: string, current: string, wordEnd: number)
321
448
  * and silently drops every control structure after the arrow.
322
449
  */
323
450
  function findFunctionBodyBrace(body: string, from: number, to: number): number {
324
- // Walk to the parameters (if any) and step over the whole list, including
325
- // nested braces inside it.
326
- let start = from;
327
- for (; start < to; start++) {
328
- if (body[start] === '(' || body[start] === '{' || body[start] === ';') break;
329
- }
330
- let i = start;
331
- if (body[i] === '(') i = skipSpaces(body, skipBalancedParen(body, i), to);
451
+ const params = indexOfParameterList(body, from, to);
452
+ const afterParams = skipParameterList(body, params, to);
332
453
  // A return-type annotation sits between the parameter list and the body
333
- // (`function inner(): { a: number } { ... }`), and braces inside it are not
334
- // the body. When an annotation is present the body brace is located directly.
335
- if (body[skipSpaces(body, i, to)] === ':') {
336
- return findBraceAfterReturnType(body, i, to);
454
+ // (`function inner(): { a: number } { ... }`), and braces inside it are not the
455
+ // body -- so the body is located by the annotation scanner instead.
456
+ if (body[skipSpaces(body, afterParams, to)] === ':') {
457
+ return findBraceAfterReturnType(body, afterParams, to);
458
+ }
459
+ return indexOfBodyBrace(body, afterParams, to);
460
+ }
461
+
462
+ /**
463
+ * Index of the parameter list's `(`, or of whatever ends the intro first.
464
+ *
465
+ * Stops at `(`, `{` or `;`: the first is the parameter list, the second means the body
466
+ * began without one, and the third means there is no body at all.
467
+ */
468
+ function indexOfParameterList(body: string, from: number, to: number): number {
469
+ for (let i = from; i < to; i++) {
470
+ if (body[i] === '(' || body[i] === '{' || body[i] === ';') return i;
337
471
  }
338
- for (; i < to; i++) {
472
+ return to;
473
+ }
474
+
475
+ /** Step over the whole parameter list, including braces nested inside it. */
476
+ function skipParameterList(body: string, at: number, to: number): number {
477
+ if (body[at] !== '(') return at;
478
+ return skipSpaces(body, skipBalancedParen(body, at), to);
479
+ }
480
+
481
+ /**
482
+ * The body's `{`, or -1 when there is none.
483
+ *
484
+ * A `;` or `}` before any brace means an expression-bodied arrow, or a `function` whose
485
+ * `{` never appears. -1 makes the caller RESUME its own scan rather than skip a bogus
486
+ * range -- a wrong range would swallow every function after it.
487
+ */
488
+ function indexOfBodyBrace(body: string, from: number, to: number): number {
489
+ for (let i = from; i < to; i++) {
339
490
  if (body[i] === '{') return i;
340
- // No braced body before the statement ends: an expression-bodied arrow or a
341
- // `function` whose `{` never appears. Report -1 so the caller resumes the
342
- // scan instead of skipping a bogus range.
343
491
  if (body[i] === ';' || body[i] === '}') return -1;
344
492
  }
345
493
  return -1;
@@ -397,45 +545,157 @@ function findBraceAfterReturnType(body: string, from: number, to: number): numbe
397
545
  let i = skipSpaces(body, from, to);
398
546
  if (body[i] !== ':') return i;
399
547
  i = skipSpaces(body, i + 1, to);
400
- let angles = 0;
401
- for (; i < to; i++) {
402
- const c = body[i];
403
- if (c === ';' || c === '\n') return -1;
404
- if (c === '<') { angles++; continue; }
405
- if (c === '>' && angles > 0) { angles--; continue; }
406
- if (c !== '{') continue;
407
- const afterBrace = skipBalancedBrace(body, i);
408
- // Inside `<>` the braces are type arguments (`Promise<{ok:boolean}>`).
409
- if (angles > 0) { i = afterBrace - 1; continue; }
410
- const rest = skipSpaces(body, afterBrace, to);
411
- if (rest >= to) return i;
412
- // A `|`/`&`/`[` continues the type; another `{` means this brace was an
413
- // object type and the real body follows (`m(): {a:number} { ... }`).
414
- if ('|&'.includes(body[rest]) || body[rest] === '[') { i = afterBrace - 1; continue; }
415
- return body[rest] === '{' ? rest : i;
548
+
549
+ return scanReturnTypeForBrace(body, i, to);
550
+ }
551
+
552
+ /**
553
+ * Walk a return type looking for the function body's `{`.
554
+ *
555
+ * A `;` or a newline before any body brace means the header has NO braced body -- an
556
+ * overload signature or an abstract method -- and the caller must not skip anything.
557
+ * Skipping a range here would swallow the next declaration.
558
+ *
559
+ * @returns the body brace (or the index just past an object type), or -1
560
+ */
561
+ function scanReturnTypeForBrace(body: string, from: number, to: number): number {
562
+ const state = { angles: 0 };
563
+ for (let i = from; i < to; i++) {
564
+ const step = returnTypeStep(body, i, to, state);
565
+ if (step.done !== undefined) return step.done;
566
+ i = step.resume;
416
567
  }
417
568
  return -1;
418
569
  }
419
570
 
571
+ /**
572
+ * Advance the return-type scan by one step.
573
+ *
574
+ * `done` carries the final answer when the scan ended; `resume` is where the caller
575
+ * continues. The `- 1` compensates for the loop's own `i++`, which is why it lives here
576
+ * rather than at each call site.
577
+ */
578
+ function returnTypeStep(
579
+ body: string,
580
+ i: number,
581
+ to: number,
582
+ state: { angles: number },
583
+ ): { done?: number; resume: number } {
584
+ const c = body[i];
585
+ if (c === ';' || c === '\n') return { done: -1, resume: i };
586
+ state.angles = adjustAngleDepth(c, state.angles);
587
+ if (c !== '{') return { resume: i };
588
+
589
+ const brace = classifyReturnBrace(body, i, state.angles, to);
590
+ if (brace.kind === 'type') return { resume: brace.next - 1 };
591
+ return { done: brace.kind === 'body-after' ? brace.next : i, resume: i };
592
+ }
593
+
594
+ /**
595
+ * Track `<` / `>` depth, which tells type arguments from comparison operators.
596
+ *
597
+ * @param {string} c the character
598
+ * @param {number} angles current depth
599
+ * @returns {number} the new depth
600
+ */
601
+ function adjustAngleDepth(c: string, angles: number): number {
602
+ if (c === '<') return angles + 1;
603
+ if (c === '>' && angles > 0) return angles - 1;
604
+ return angles;
605
+ }
606
+
607
+ /**
608
+ * What the `{` at `i` is, when scanning a return type.
609
+ *
610
+ * Inside `<>` a brace belongs to a type argument (`Promise<{ok:boolean}>`) and the
611
+ * scan simply continues. At depth 0 it is either the function BODY -- what the caller
612
+ * wants -- or an object TYPE, in which case the real body follows it
613
+ * (`m(): {a:number} { ... }`), recognised by a `|`/`&`/`[` continuing the type or by
614
+ * another `{` after it.
615
+ *
616
+ * @returns {{kind: 'type'|'body'|'body-after', next: number}} `next` is the index to
617
+ * resume from; for 'body-after' it is the real body's `{`
618
+ */
619
+ function classifyReturnBrace(body: string, i: number, angles: number, to: number) {
620
+ const afterBrace = skipBalancedBrace(body, i);
621
+ if (angles > 0) return { kind: 'type', next: afterBrace };
622
+
623
+ const rest = skipSpaces(body, afterBrace, to);
624
+ if (rest >= to) return { kind: 'body', next: i };
625
+ if (typeContinuesAt(body[rest])) return { kind: 'type', next: afterBrace };
626
+ return body[rest] === '{' ? { kind: 'body-after', next: rest } : { kind: 'body', next: i };
627
+ }
628
+
629
+ /**
630
+ * Whether this character CONTINUES an object type rather than starting the body.
631
+ *
632
+ * A union/intersection (`|`, `&`) or an indexed access (`[`) proves the brace just
633
+ * closed was a TYPE -- `m(): {a:number} | null { ... }` -- so the scan must keep looking
634
+ * for the real body instead of stopping there.
635
+ */
636
+ function typeContinuesAt(c: string): boolean {
637
+ return c === '|' || c === '&' || c === '[';
638
+ }
639
+
420
640
  /** One classified step of an arrow return-type scan. */
421
641
  type TypeScanStep = 'stop' | 'open-brace' | 'close-brace' | 'open-angle' | 'close-angle' | 'skip';
422
642
 
423
643
  /**
424
- * Classify one character of an arrow's return type. An arrow's return type may
425
- * itself be an object literal (`(x): { ok: boolean } =>`), so a `{` opens a type
426
- * brace.
644
+ * Characters that open a type-level brace or angle, and the step each reports.
645
+ *
646
+ * A lookup because the classification is per CHARACTER; the two cases that depend on
647
+ * depth (`}` and flat-only terminators) are handled before this is consulted and must
648
+ * not be moved into it.
649
+ */
650
+ const TYPE_STEPS: Record<string, TypeScanStep> = {
651
+ '{': 'open-brace',
652
+ '<': 'open-angle',
653
+ };
654
+
655
+ /** Characters that end a type scan at depth 0: the arrow, or the statement end. */
656
+ const TYPE_TERMINATORS = new Set([';', '\n']);
657
+
658
+ /**
659
+ * Classify one character of an arrow's return type.
660
+ *
661
+ * An arrow's return type may itself be an object literal (`(x): { ok: boolean } =>`),
662
+ * so a `{` opens a TYPE brace rather than ending the scan -- which is why this cannot
663
+ * simply stop at the first brace it sees.
664
+ *
665
+ * `}` needs the depth to be read before it can be classified: at depth 0 it closes the
666
+ * ENCLOSING block, so the type cannot extend past it.
667
+ *
668
+ * @returns the step
427
669
  */
428
670
  function classifyTypeChar(body: string, i: number, braces: number, angles: number): TypeScanStep {
429
671
  const c = body[i];
430
- if (c === '{') return 'open-brace';
431
- // A `}` at depth 0 closes the enclosing block, so the type cannot extend past it.
432
- if (c === '}') return braces === 0 ? 'stop' : 'close-brace';
433
- if (c === '<') return 'open-angle';
434
- if (c === '>' && angles > 0) return 'close-angle';
672
+ if (c === '}') return closingBraceStep(braces);
673
+ if (isFlatEnd(body, i, braces, angles)) return 'stop';
674
+ return TYPE_STEPS[c] || 'skip';
675
+ }
676
+
677
+ /**
678
+ * What a `}` means to a type scan.
679
+ *
680
+ * At depth 0 it closes the block the scan is running INSIDE, so the type cannot extend
681
+ * past it -- that is the end of the scan, not a type brace closing.
682
+ */
683
+ function closingBraceStep(braces: number): TypeScanStep {
684
+ return braces === 0 ? 'stop' : 'close-brace';
685
+ }
686
+
687
+ /**
688
+ * Whether the character at `i` ends the type at the OUTERMOST level.
689
+ *
690
+ * Only at the outermost level: `;` and a newline inside a type brace or a generic
691
+ * argument are part of the type (`{ a: number; b: string }`).
692
+ */
693
+ function isFlatEnd(body: string, i: number, braces: number, angles: number): boolean {
435
694
  const flat = braces === 0 && angles === 0;
436
- if (flat && c === '=' && body[i + 1] === '>') return 'stop';
437
- if (flat && (c === ';' || c === '\n')) return 'stop';
438
- return 'skip';
695
+ if (!flat) return false;
696
+ const c = body[i];
697
+ if (c === '=' && body[i + 1] === '>') return true;
698
+ return TYPE_TERMINATORS.has(c);
439
699
  }
440
700
 
441
701
  /** Depth adjustment for one step of a type scan. */
@@ -529,40 +789,93 @@ const PAIR_CONSUMED = 2;
529
789
  *
530
790
  * @returns `PAIR_CONSUMED` when a two-character pair was consumed whole, else 1.
531
791
  */
792
+ /** A line comment ends at the newline, which is consumed with it. */
793
+ function advanceLineComment(c: string, state: NestingScanState): number {
794
+ if (c === '\n') state.inLineComment = false;
795
+ return 1;
796
+ }
797
+
798
+ /** A block comment ends at the slash-star closing pair, so that pair consumes two. */
799
+ function advanceBlockComment(c: string, next: string, state: NestingScanState): number {
800
+ if (c === '*' && next === '/') {
801
+ state.inBlockComment = false;
802
+ return 2;
803
+ }
804
+ return 1;
805
+ }
806
+
807
+ /**
808
+ * Inside a string: a backslash escapes the next character, the closing quote ends it.
809
+ *
810
+ * @param close called when the quote closes the context
811
+ */
812
+ function advanceString(c: string, next: string, quote: string, close: () => void): number {
813
+ if (c === '\\') return 2;
814
+ if (c === quote) close();
815
+ return 1;
816
+ }
817
+
818
+ /**
819
+ * The string-like contexts, and how each closes.
820
+ *
821
+ * A table rather than a chain of `if (state.inX)`: the three contexts share one shape
822
+ * (escape consumes two, the closing quote ends it, everything else consumes one) and
823
+ * differ only in the quote character.
824
+ */
825
+ const STRING_CONTEXTS: Array<{ flag: 'inSingle' | 'inDouble' | 'inTemplate'; quote: string }> = [
826
+ { flag: 'inSingle', quote: "'" },
827
+ { flag: 'inDouble', quote: '"' },
828
+ { flag: 'inTemplate', quote: '`' },
829
+ ];
830
+
831
+ /**
832
+ * Recognise an opening comment or string delimiter, when no context is active.
833
+ *
834
+ * The order in `advanceNestingState` matters and is the whole algorithm: an opening
835
+ * delimiter is only seen when nothing else is active, so a slash-slash inside a
836
+ * string stays data and a quote inside a comment stays a comment.
837
+ *
838
+ * @returns characters consumed: 2 for a comment opener, 1 otherwise
839
+ */
840
+ /** The two comment forms a `/` may open. */
841
+ const COMMENT_OPENERS: Record<string, keyof NestingScanState> = {
842
+ '/': 'inLineComment',
843
+ '*': 'inBlockComment',
844
+ };
845
+
846
+ function openContext(c: string, next: string, state: NestingScanState): number {
847
+ // A `//` or `/*` opener consumes BOTH characters; a quote consumes one and leaves the
848
+ // body to the string-context scanner.
849
+ const comment = c === '/' ? COMMENT_OPENERS[next] : undefined;
850
+ if (comment) {
851
+ (state[comment] as boolean) = true;
852
+ return 2;
853
+ }
854
+ const opened = STRING_CONTEXTS.find((ctx) => ctx.quote === c);
855
+ if (opened) state[opened.flag] = true;
856
+ return 1;
857
+ }
858
+
859
+ /** The active string context for this state, if any. */
860
+ function activeStringContext(state: NestingScanState) {
861
+ return STRING_CONTEXTS.find((ctx) => state[ctx.flag]);
862
+ }
863
+
864
+ /**
865
+ * Advance one lexical token, returning how many characters it consumed.
866
+ */
532
867
  function advanceNestingState(body: string, i: number, state: NestingScanState): number {
533
868
  const c = body[i];
534
869
  const next = body[i + 1];
535
870
 
536
- if (state.inLineComment) {
537
- if (c === '\n') state.inLineComment = false;
538
- return 1;
539
- }
540
- if (state.inBlockComment) {
541
- if (c === '*' && next === '/') { state.inBlockComment = false; return 2; }
542
- return 1;
543
- }
544
- if (state.inSingle) {
545
- if (c === '\\') return 2;
546
- if (c === "'") state.inSingle = false;
547
- return 1;
548
- }
549
- if (state.inDouble) {
550
- if (c === '\\') return 2;
551
- if (c === '"') state.inDouble = false;
552
- return 1;
553
- }
554
- if (state.inTemplate) {
555
- if (c === '\\') return 2;
556
- if (c === '`') state.inTemplate = false;
557
- return 1;
558
- }
871
+ if (state.inLineComment) return advanceLineComment(c, state);
872
+ if (state.inBlockComment) return advanceBlockComment(c, next, state);
559
873
 
560
- if (c === '/' && next === '/') { state.inLineComment = true; return 2; }
561
- if (c === '/' && next === '*') { state.inBlockComment = true; return 2; }
562
- if (c === "'") state.inSingle = true;
563
- else if (c === '"') state.inDouble = true;
564
- else if (c === '`') state.inTemplate = true;
565
- return 1;
874
+ const context = activeStringContext(state);
875
+ if (context) {
876
+ return advanceString(c, next, context.quote, () => { state[context.flag] = false; });
877
+ }
878
+ return openContext(c, next, state);
566
879
  }
567
880
 
568
881
  /** True when the current state's character carries structure, not data. */