@typespec/compiler 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +9 -0
  3. package/cmd/tsp-server.js +3 -0
  4. package/cmd/tsp.js +3 -0
  5. package/dist/cmd/runner.d.ts +9 -0
  6. package/dist/cmd/runner.d.ts.map +1 -0
  7. package/dist/cmd/runner.js +62 -0
  8. package/dist/cmd/runner.js.map +1 -0
  9. package/dist/config/config-interpolation.d.ts +11 -0
  10. package/dist/config/config-interpolation.d.ts.map +1 -0
  11. package/dist/config/config-interpolation.js +109 -0
  12. package/dist/config/config-interpolation.js.map +1 -0
  13. package/dist/config/config-loader.d.ts +25 -0
  14. package/dist/config/config-loader.d.ts.map +1 -0
  15. package/dist/config/config-loader.js +182 -0
  16. package/dist/config/config-loader.js.map +1 -0
  17. package/dist/config/config-schema.d.ts +4 -0
  18. package/dist/config/config-schema.d.ts.map +1 -0
  19. package/dist/config/config-schema.js +84 -0
  20. package/dist/config/config-schema.js.map +1 -0
  21. package/dist/config/index.d.ts +3 -0
  22. package/dist/config/index.d.ts.map +1 -0
  23. package/dist/config/index.js +3 -0
  24. package/dist/config/index.js.map +1 -0
  25. package/dist/config/types.d.ts +79 -0
  26. package/dist/config/types.d.ts.map +1 -0
  27. package/dist/config/types.js +2 -0
  28. package/dist/config/types.js.map +1 -0
  29. package/dist/core/binder.d.ts +29 -0
  30. package/dist/core/binder.d.ts.map +1 -0
  31. package/dist/core/binder.js +455 -0
  32. package/dist/core/binder.js.map +1 -0
  33. package/dist/core/charcode.d.ts +130 -0
  34. package/dist/core/charcode.d.ts.map +1 -0
  35. package/dist/core/charcode.js +115 -0
  36. package/dist/core/charcode.js.map +1 -0
  37. package/dist/core/checker.d.ts +138 -0
  38. package/dist/core/checker.d.ts.map +1 -0
  39. package/dist/core/checker.js +4070 -0
  40. package/dist/core/checker.js.map +1 -0
  41. package/dist/core/cli/args.d.ts +18 -0
  42. package/dist/core/cli/args.d.ts.map +1 -0
  43. package/dist/core/cli/args.js +108 -0
  44. package/dist/core/cli/args.js.map +1 -0
  45. package/dist/core/cli/cli.d.ts +2 -0
  46. package/dist/core/cli/cli.d.ts.map +1 -0
  47. package/dist/core/cli/cli.js +477 -0
  48. package/dist/core/cli/cli.js.map +1 -0
  49. package/dist/core/cli/index.d.ts +2 -0
  50. package/dist/core/cli/index.d.ts.map +1 -0
  51. package/dist/core/cli/index.js +2 -0
  52. package/dist/core/cli/index.js.map +1 -0
  53. package/dist/core/decorator-utils.d.ts +108 -0
  54. package/dist/core/decorator-utils.d.ts.map +1 -0
  55. package/dist/core/decorator-utils.js +326 -0
  56. package/dist/core/decorator-utils.js.map +1 -0
  57. package/dist/core/diagnostics.d.ts +93 -0
  58. package/dist/core/diagnostics.d.ts.map +1 -0
  59. package/dist/core/diagnostics.js +315 -0
  60. package/dist/core/diagnostics.js.map +1 -0
  61. package/dist/core/emitter-utils.d.ts +14 -0
  62. package/dist/core/emitter-utils.d.ts.map +1 -0
  63. package/dist/core/emitter-utils.js +16 -0
  64. package/dist/core/emitter-utils.js.map +1 -0
  65. package/dist/core/formatter-fs.d.ts +21 -0
  66. package/dist/core/formatter-fs.d.ts.map +1 -0
  67. package/dist/core/formatter-fs.js +79 -0
  68. package/dist/core/formatter-fs.js.map +1 -0
  69. package/dist/core/formatter.d.ts +10 -0
  70. package/dist/core/formatter.d.ts.map +1 -0
  71. package/dist/core/formatter.js +24 -0
  72. package/dist/core/formatter.js.map +1 -0
  73. package/dist/core/helpers/discriminator-utils.d.ts +14 -0
  74. package/dist/core/helpers/discriminator-utils.d.ts.map +1 -0
  75. package/dist/core/helpers/discriminator-utils.js +169 -0
  76. package/dist/core/helpers/discriminator-utils.js.map +1 -0
  77. package/dist/core/helpers/index.d.ts +6 -0
  78. package/dist/core/helpers/index.d.ts.map +1 -0
  79. package/dist/core/helpers/index.js +6 -0
  80. package/dist/core/helpers/index.js.map +1 -0
  81. package/dist/core/helpers/operation-utils.d.ts +15 -0
  82. package/dist/core/helpers/operation-utils.d.ts.map +1 -0
  83. package/dist/core/helpers/operation-utils.js +35 -0
  84. package/dist/core/helpers/operation-utils.js.map +1 -0
  85. package/dist/core/helpers/projected-names-utils.d.ts +20 -0
  86. package/dist/core/helpers/projected-names-utils.d.ts.map +1 -0
  87. package/dist/core/helpers/projected-names-utils.js +40 -0
  88. package/dist/core/helpers/projected-names-utils.js.map +1 -0
  89. package/dist/core/helpers/type-name-utils.d.ts +14 -0
  90. package/dist/core/helpers/type-name-utils.d.ts.map +1 -0
  91. package/dist/core/helpers/type-name-utils.js +122 -0
  92. package/dist/core/helpers/type-name-utils.js.map +1 -0
  93. package/dist/core/helpers/usage-resolver.d.ts +20 -0
  94. package/dist/core/helpers/usage-resolver.d.ts.map +1 -0
  95. package/dist/core/helpers/usage-resolver.js +108 -0
  96. package/dist/core/helpers/usage-resolver.js.map +1 -0
  97. package/dist/core/index.d.ts +26 -0
  98. package/dist/core/index.d.ts.map +1 -0
  99. package/dist/core/index.js +26 -0
  100. package/dist/core/index.js.map +1 -0
  101. package/dist/core/install.d.ts +2 -0
  102. package/dist/core/install.d.ts.map +1 -0
  103. package/dist/core/install.js +26 -0
  104. package/dist/core/install.js.map +1 -0
  105. package/dist/core/library.d.ts +34 -0
  106. package/dist/core/library.d.ts.map +1 -0
  107. package/dist/core/library.js +100 -0
  108. package/dist/core/library.js.map +1 -0
  109. package/dist/core/logger/console-sink.browser.d.ts +4 -0
  110. package/dist/core/logger/console-sink.browser.d.ts.map +1 -0
  111. package/dist/core/logger/console-sink.browser.js +14 -0
  112. package/dist/core/logger/console-sink.browser.js.map +1 -0
  113. package/dist/core/logger/console-sink.d.ts +9 -0
  114. package/dist/core/logger/console-sink.d.ts.map +1 -0
  115. package/dist/core/logger/console-sink.js +81 -0
  116. package/dist/core/logger/console-sink.js.map +1 -0
  117. package/dist/core/logger/index.d.ts +3 -0
  118. package/dist/core/logger/index.d.ts.map +1 -0
  119. package/dist/core/logger/index.js +3 -0
  120. package/dist/core/logger/index.js.map +1 -0
  121. package/dist/core/logger/logger.d.ts +7 -0
  122. package/dist/core/logger/logger.d.ts.map +1 -0
  123. package/dist/core/logger/logger.js +32 -0
  124. package/dist/core/logger/logger.js.map +1 -0
  125. package/dist/core/logger/tracer.d.ts +3 -0
  126. package/dist/core/logger/tracer.d.ts.map +1 -0
  127. package/dist/core/logger/tracer.js +91 -0
  128. package/dist/core/logger/tracer.js.map +1 -0
  129. package/dist/core/manifest.d.ts +21 -0
  130. package/dist/core/manifest.d.ts.map +1 -0
  131. package/dist/core/manifest.js +8 -0
  132. package/dist/core/manifest.js.map +1 -0
  133. package/dist/core/messages.d.ts +2253 -0
  134. package/dist/core/messages.d.ts.map +1 -0
  135. package/dist/core/messages.js +749 -0
  136. package/dist/core/messages.js.map +1 -0
  137. package/dist/core/module-resolver.d.ts +84 -0
  138. package/dist/core/module-resolver.d.ts.map +1 -0
  139. package/dist/core/module-resolver.js +170 -0
  140. package/dist/core/module-resolver.js.map +1 -0
  141. package/dist/core/node-host.browser.d.ts +2 -0
  142. package/dist/core/node-host.browser.d.ts.map +1 -0
  143. package/dist/core/node-host.browser.js +2 -0
  144. package/dist/core/node-host.browser.js.map +1 -0
  145. package/dist/core/node-host.d.ts +7 -0
  146. package/dist/core/node-host.d.ts.map +1 -0
  147. package/dist/core/node-host.js +43 -0
  148. package/dist/core/node-host.js.map +1 -0
  149. package/dist/core/nonascii.d.ts +2 -0
  150. package/dist/core/nonascii.d.ts.map +1 -0
  151. package/dist/core/nonascii.js +712 -0
  152. package/dist/core/nonascii.js.map +1 -0
  153. package/dist/core/options.d.ts +46 -0
  154. package/dist/core/options.d.ts.map +1 -0
  155. package/dist/core/options.js +2 -0
  156. package/dist/core/options.js.map +1 -0
  157. package/dist/core/parser.d.ts +17 -0
  158. package/dist/core/parser.d.ts.map +1 -0
  159. package/dist/core/parser.js +2561 -0
  160. package/dist/core/parser.js.map +1 -0
  161. package/dist/core/path-utils.d.ts +193 -0
  162. package/dist/core/path-utils.d.ts.map +1 -0
  163. package/dist/core/path-utils.js +427 -0
  164. package/dist/core/path-utils.js.map +1 -0
  165. package/dist/core/program.d.ts +104 -0
  166. package/dist/core/program.d.ts.map +1 -0
  167. package/dist/core/program.js +898 -0
  168. package/dist/core/program.js.map +1 -0
  169. package/dist/core/projection-members.d.ts +8 -0
  170. package/dist/core/projection-members.d.ts.map +1 -0
  171. package/dist/core/projection-members.js +387 -0
  172. package/dist/core/projection-members.js.map +1 -0
  173. package/dist/core/projector.d.ts +26 -0
  174. package/dist/core/projector.d.ts.map +1 -0
  175. package/dist/core/projector.js +523 -0
  176. package/dist/core/projector.js.map +1 -0
  177. package/dist/core/scanner.d.ts +125 -0
  178. package/dist/core/scanner.d.ts.map +1 -0
  179. package/dist/core/scanner.js +1012 -0
  180. package/dist/core/scanner.js.map +1 -0
  181. package/dist/core/schema-validator.d.ts +6 -0
  182. package/dist/core/schema-validator.d.ts.map +1 -0
  183. package/dist/core/schema-validator.js +38 -0
  184. package/dist/core/schema-validator.js.map +1 -0
  185. package/dist/core/semantic-walker.d.ts +53 -0
  186. package/dist/core/semantic-walker.d.ts.map +1 -0
  187. package/dist/core/semantic-walker.js +355 -0
  188. package/dist/core/semantic-walker.js.map +1 -0
  189. package/dist/core/type-utils.d.ts +49 -0
  190. package/dist/core/type-utils.d.ts.map +1 -0
  191. package/dist/core/type-utils.js +95 -0
  192. package/dist/core/type-utils.js.map +1 -0
  193. package/dist/core/types.d.ts +1345 -0
  194. package/dist/core/types.d.ts.map +1 -0
  195. package/dist/core/types.js +105 -0
  196. package/dist/core/types.js.map +1 -0
  197. package/dist/core/util.d.ts +150 -0
  198. package/dist/core/util.d.ts.map +1 -0
  199. package/dist/core/util.js +417 -0
  200. package/dist/core/util.js.map +1 -0
  201. package/dist/emitter-framework/asset-emitter.d.ts +5 -0
  202. package/dist/emitter-framework/asset-emitter.d.ts.map +1 -0
  203. package/dist/emitter-framework/asset-emitter.js +610 -0
  204. package/dist/emitter-framework/asset-emitter.js.map +1 -0
  205. package/dist/emitter-framework/builders/array-builder.d.ts +7 -0
  206. package/dist/emitter-framework/builders/array-builder.d.ts.map +1 -0
  207. package/dist/emitter-framework/builders/array-builder.js +45 -0
  208. package/dist/emitter-framework/builders/array-builder.js.map +1 -0
  209. package/dist/emitter-framework/builders/object-builder.d.ts +9 -0
  210. package/dist/emitter-framework/builders/object-builder.d.ts.map +1 -0
  211. package/dist/emitter-framework/builders/object-builder.js +30 -0
  212. package/dist/emitter-framework/builders/object-builder.js.map +1 -0
  213. package/dist/emitter-framework/builders/string-builder.d.ts +13 -0
  214. package/dist/emitter-framework/builders/string-builder.d.ts.map +1 -0
  215. package/dist/emitter-framework/builders/string-builder.js +98 -0
  216. package/dist/emitter-framework/builders/string-builder.js.map +1 -0
  217. package/dist/emitter-framework/custom-key-map.d.ts +29 -0
  218. package/dist/emitter-framework/custom-key-map.d.ts.map +1 -0
  219. package/dist/emitter-framework/custom-key-map.js +62 -0
  220. package/dist/emitter-framework/custom-key-map.js.map +1 -0
  221. package/dist/emitter-framework/index.d.ts +8 -0
  222. package/dist/emitter-framework/index.d.ts.map +1 -0
  223. package/dist/emitter-framework/index.js +8 -0
  224. package/dist/emitter-framework/index.js.map +1 -0
  225. package/dist/emitter-framework/placeholder.d.ts +12 -0
  226. package/dist/emitter-framework/placeholder.d.ts.map +1 -0
  227. package/dist/emitter-framework/placeholder.js +27 -0
  228. package/dist/emitter-framework/placeholder.js.map +1 -0
  229. package/dist/emitter-framework/type-emitter.d.ts +314 -0
  230. package/dist/emitter-framework/type-emitter.d.ts.map +1 -0
  231. package/dist/emitter-framework/type-emitter.js +612 -0
  232. package/dist/emitter-framework/type-emitter.js.map +1 -0
  233. package/dist/emitter-framework/types.d.ts +124 -0
  234. package/dist/emitter-framework/types.d.ts.map +1 -0
  235. package/dist/emitter-framework/types.js +39 -0
  236. package/dist/emitter-framework/types.js.map +1 -0
  237. package/dist/formatter/index.d.ts +11 -0
  238. package/dist/formatter/index.d.ts.map +1 -0
  239. package/dist/formatter/index.js +28 -0
  240. package/dist/formatter/index.js.map +1 -0
  241. package/dist/formatter/parser.d.ts +16 -0
  242. package/dist/formatter/parser.d.ts.map +1 -0
  243. package/dist/formatter/parser.js +23 -0
  244. package/dist/formatter/parser.js.map +1 -0
  245. package/dist/formatter/print/comment-handler.d.ts +7 -0
  246. package/dist/formatter/print/comment-handler.d.ts.map +1 -0
  247. package/dist/formatter/print/comment-handler.js +81 -0
  248. package/dist/formatter/print/comment-handler.js.map +1 -0
  249. package/dist/formatter/print/index.d.ts +3 -0
  250. package/dist/formatter/print/index.d.ts.map +1 -0
  251. package/dist/formatter/print/index.js +3 -0
  252. package/dist/formatter/print/index.js.map +1 -0
  253. package/dist/formatter/print/needs-parens.d.ts +10 -0
  254. package/dist/formatter/print/needs-parens.d.ts.map +1 -0
  255. package/dist/formatter/print/needs-parens.js +27 -0
  256. package/dist/formatter/print/needs-parens.js.map +1 -0
  257. package/dist/formatter/print/printer.d.ts +62 -0
  258. package/dist/formatter/print/printer.d.ts.map +1 -0
  259. package/dist/formatter/print/printer.js +1025 -0
  260. package/dist/formatter/print/printer.js.map +1 -0
  261. package/dist/formatter/print/types.d.ts +9 -0
  262. package/dist/formatter/print/types.d.ts.map +1 -0
  263. package/dist/formatter/print/types.js +2 -0
  264. package/dist/formatter/print/types.js.map +1 -0
  265. package/dist/init/index.d.ts +2 -0
  266. package/dist/init/index.d.ts.map +1 -0
  267. package/dist/init/index.js +2 -0
  268. package/dist/init/index.js.map +1 -0
  269. package/dist/init/init-template.d.ts +45 -0
  270. package/dist/init/init-template.d.ts.map +1 -0
  271. package/dist/init/init-template.js +45 -0
  272. package/dist/init/init-template.js.map +1 -0
  273. package/dist/init/init.d.ts +49 -0
  274. package/dist/init/init.d.ts.map +1 -0
  275. package/dist/init/init.js +224 -0
  276. package/dist/init/init.js.map +1 -0
  277. package/dist/lib/decorators.d.ts +222 -0
  278. package/dist/lib/decorators.d.ts.map +1 -0
  279. package/dist/lib/decorators.js +745 -0
  280. package/dist/lib/decorators.js.map +1 -0
  281. package/dist/lib/service.d.ts +38 -0
  282. package/dist/lib/service.d.ts.map +1 -0
  283. package/dist/lib/service.js +78 -0
  284. package/dist/lib/service.js.map +1 -0
  285. package/dist/manifest.js +4 -0
  286. package/dist/server/completion.d.ts +10 -0
  287. package/dist/server/completion.d.ts.map +1 -0
  288. package/dist/server/completion.js +207 -0
  289. package/dist/server/completion.js.map +1 -0
  290. package/dist/server/index.d.ts +3 -0
  291. package/dist/server/index.d.ts.map +1 -0
  292. package/dist/server/index.js +3 -0
  293. package/dist/server/index.js.map +1 -0
  294. package/dist/server/language-config.d.ts +195 -0
  295. package/dist/server/language-config.d.ts.map +1 -0
  296. package/dist/server/language-config.js +102 -0
  297. package/dist/server/language-config.js.map +1 -0
  298. package/dist/server/server.d.ts +2 -0
  299. package/dist/server/server.d.ts.map +1 -0
  300. package/dist/server/server.js +131 -0
  301. package/dist/server/server.js.map +1 -0
  302. package/dist/server/serverlib.d.ts +72 -0
  303. package/dist/server/serverlib.d.ts.map +1 -0
  304. package/dist/server/serverlib.js +1034 -0
  305. package/dist/server/serverlib.js.map +1 -0
  306. package/dist/server/symbol-structure.d.ts +4 -0
  307. package/dist/server/symbol-structure.d.ts.map +1 -0
  308. package/dist/server/symbol-structure.js +121 -0
  309. package/dist/server/symbol-structure.js.map +1 -0
  310. package/dist/server/tmlanguage.d.ts +3 -0
  311. package/dist/server/tmlanguage.d.ts.map +1 -0
  312. package/dist/server/tmlanguage.js +713 -0
  313. package/dist/server/tmlanguage.js.map +1 -0
  314. package/dist/server/type-details.d.ts +11 -0
  315. package/dist/server/type-details.d.ts.map +1 -0
  316. package/dist/server/type-details.js +72 -0
  317. package/dist/server/type-details.js.map +1 -0
  318. package/dist/server/type-signature.d.ts +2 -0
  319. package/dist/server/type-signature.d.ts.map +1 -0
  320. package/dist/server/type-signature.js +108 -0
  321. package/dist/server/type-signature.js.map +1 -0
  322. package/dist/testing/expect.d.ts +49 -0
  323. package/dist/testing/expect.d.ts.map +1 -0
  324. package/dist/testing/expect.js +83 -0
  325. package/dist/testing/expect.js.map +1 -0
  326. package/dist/testing/index.d.ts +6 -0
  327. package/dist/testing/index.d.ts.map +1 -0
  328. package/dist/testing/index.js +6 -0
  329. package/dist/testing/index.js.map +1 -0
  330. package/dist/testing/test-host.d.ts +14 -0
  331. package/dist/testing/test-host.d.ts.map +1 -0
  332. package/dist/testing/test-host.js +271 -0
  333. package/dist/testing/test-host.js.map +1 -0
  334. package/dist/testing/test-server-host.d.ts +39 -0
  335. package/dist/testing/test-server-host.d.ts.map +1 -0
  336. package/dist/testing/test-server-host.js +112 -0
  337. package/dist/testing/test-server-host.js.map +1 -0
  338. package/dist/testing/test-utils.d.ts +22 -0
  339. package/dist/testing/test-utils.d.ts.map +1 -0
  340. package/dist/testing/test-utils.js +60 -0
  341. package/dist/testing/test-utils.js.map +1 -0
  342. package/dist/testing/types.d.ts +69 -0
  343. package/dist/testing/types.d.ts.map +1 -0
  344. package/dist/testing/types.js +7 -0
  345. package/dist/testing/types.js.map +1 -0
  346. package/dist/typespec.tmLanguage +1760 -0
  347. package/lib/decorators.tsp +420 -0
  348. package/lib/lib.tsp +158 -0
  349. package/lib/main.tsp +4 -0
  350. package/lib/projected-names.tsp +94 -0
  351. package/lib/reflection.tsp +10 -0
  352. package/package.json +119 -0
@@ -0,0 +1,1034 @@
1
+ import { Diagnostic as VSDiagnostic, DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, MarkupKind, Range, SemanticTokensBuilder, TextDocumentSyncKind, TextEdit, } from "vscode-languageserver/node.js";
2
+ import { defaultConfig, findTypeSpecConfigPath, loadTypeSpecConfigFile, } from "../config/config-loader.js";
3
+ import { codePointBefore, isIdentifierContinue } from "../core/charcode.js";
4
+ import { compilerAssert, createSourceFile, formatDiagnostic, getSourceLocation, } from "../core/diagnostics.js";
5
+ import { formatTypeSpec } from "../core/formatter.js";
6
+ import { getTypeName } from "../core/helpers/type-name-utils.js";
7
+ import { getNodeAtPosition, visitChildren } from "../core/parser.js";
8
+ import { ensureTrailingDirectorySeparator, getDirectoryPath, joinPaths, } from "../core/path-utils.js";
9
+ import { compile as compileProgram } from "../core/program.js";
10
+ import { createScanner, isKeyword, isPunctuation, skipTrivia, skipWhiteSpace, Token, } from "../core/scanner.js";
11
+ import { SyntaxKind, } from "../core/types.js";
12
+ import { doIO, getNormalizedRealPath, getSourceFileKindFromExt, loadFile, resolveTspMain, } from "../core/util.js";
13
+ import { resolveCompletion } from "./completion.js";
14
+ import { getSymbolStructure } from "./symbol-structure.js";
15
+ import { getParameterDocumentation, getTypeDetails } from "./type-details.js";
16
+ export var SemanticTokenKind;
17
+ (function (SemanticTokenKind) {
18
+ SemanticTokenKind[SemanticTokenKind["Namespace"] = 0] = "Namespace";
19
+ SemanticTokenKind[SemanticTokenKind["Type"] = 1] = "Type";
20
+ SemanticTokenKind[SemanticTokenKind["Class"] = 2] = "Class";
21
+ SemanticTokenKind[SemanticTokenKind["Enum"] = 3] = "Enum";
22
+ SemanticTokenKind[SemanticTokenKind["Interface"] = 4] = "Interface";
23
+ SemanticTokenKind[SemanticTokenKind["Struct"] = 5] = "Struct";
24
+ SemanticTokenKind[SemanticTokenKind["TypeParameter"] = 6] = "TypeParameter";
25
+ SemanticTokenKind[SemanticTokenKind["Parameter"] = 7] = "Parameter";
26
+ SemanticTokenKind[SemanticTokenKind["Variable"] = 8] = "Variable";
27
+ SemanticTokenKind[SemanticTokenKind["Property"] = 9] = "Property";
28
+ SemanticTokenKind[SemanticTokenKind["EnumMember"] = 10] = "EnumMember";
29
+ SemanticTokenKind[SemanticTokenKind["Event"] = 11] = "Event";
30
+ SemanticTokenKind[SemanticTokenKind["Function"] = 12] = "Function";
31
+ SemanticTokenKind[SemanticTokenKind["Method"] = 13] = "Method";
32
+ SemanticTokenKind[SemanticTokenKind["Macro"] = 14] = "Macro";
33
+ SemanticTokenKind[SemanticTokenKind["Keyword"] = 15] = "Keyword";
34
+ SemanticTokenKind[SemanticTokenKind["Comment"] = 16] = "Comment";
35
+ SemanticTokenKind[SemanticTokenKind["String"] = 17] = "String";
36
+ SemanticTokenKind[SemanticTokenKind["Number"] = 18] = "Number";
37
+ SemanticTokenKind[SemanticTokenKind["Regexp"] = 19] = "Regexp";
38
+ SemanticTokenKind[SemanticTokenKind["Operator"] = 20] = "Operator";
39
+ })(SemanticTokenKind = SemanticTokenKind || (SemanticTokenKind = {}));
40
+ const serverOptions = {
41
+ noEmit: true,
42
+ designTimeBuild: true,
43
+ parseOptions: {
44
+ comments: true,
45
+ docs: true,
46
+ },
47
+ };
48
+ export function createServer(host) {
49
+ // Remember original URL when we convert it to a local path so that we can
50
+ // get it back. We can't convert it back because things like URL-encoding
51
+ // could give us back an equivalent but non-identical URL but the original
52
+ // URL is used as a key into the opened documents and so we must reproduce
53
+ // it exactly.
54
+ const pathToURLMap = new Map();
55
+ // Cache all file I/O. Only open documents are sent over the LSP pipe. When
56
+ // the compiler reads a file that isn't open, we use this cache to avoid
57
+ // hitting the disk. Entries are invalidated when LSP client notifies us of
58
+ // a file change.
59
+ const fileSystemCache = createFileSystemCache();
60
+ const compilerHost = createCompilerHost();
61
+ const oldPrograms = new Map();
62
+ let workspaceFolders = [];
63
+ let isInitialized = false;
64
+ let pendingMessages = [];
65
+ return {
66
+ get pendingMessages() {
67
+ return pendingMessages;
68
+ },
69
+ get workspaceFolders() {
70
+ return workspaceFolders;
71
+ },
72
+ compile,
73
+ initialize,
74
+ initialized,
75
+ workspaceFoldersChanged,
76
+ watchedFilesChanged,
77
+ formatDocument,
78
+ gotoDefinition,
79
+ documentClosed,
80
+ complete,
81
+ findReferences,
82
+ findDocumentHighlight,
83
+ prepareRename,
84
+ rename,
85
+ getSemanticTokens,
86
+ buildSemanticTokens,
87
+ checkChange,
88
+ getFoldingRanges,
89
+ getHover,
90
+ getSignatureHelp,
91
+ getDocumentSymbols,
92
+ log,
93
+ };
94
+ async function initialize(params) {
95
+ var _a, _b;
96
+ const tokenLegend = {
97
+ tokenTypes: Object.keys(SemanticTokenKind)
98
+ .filter((x) => Number.isNaN(Number(x)))
99
+ .map((x) => x.slice(0, 1).toLocaleLowerCase() + x.slice(1)),
100
+ tokenModifiers: [],
101
+ };
102
+ const capabilities = {
103
+ textDocumentSync: TextDocumentSyncKind.Incremental,
104
+ definitionProvider: true,
105
+ foldingRangeProvider: true,
106
+ hoverProvider: true,
107
+ documentSymbolProvider: true,
108
+ documentHighlightProvider: true,
109
+ completionProvider: {
110
+ resolveProvider: false,
111
+ triggerCharacters: [".", "@", "/"],
112
+ },
113
+ semanticTokensProvider: {
114
+ full: true,
115
+ legend: tokenLegend,
116
+ },
117
+ referencesProvider: true,
118
+ renameProvider: {
119
+ prepareProvider: true,
120
+ },
121
+ documentFormattingProvider: true,
122
+ signatureHelpProvider: {
123
+ triggerCharacters: ["(", ",", "<"],
124
+ retriggerCharacters: [")"],
125
+ },
126
+ };
127
+ if ((_a = params.capabilities.workspace) === null || _a === void 0 ? void 0 : _a.workspaceFolders) {
128
+ for (const w of (_b = params.workspaceFolders) !== null && _b !== void 0 ? _b : []) {
129
+ workspaceFolders.push({
130
+ ...w,
131
+ path: ensureTrailingDirectorySeparator(await fileURLToRealPath(w.uri)),
132
+ });
133
+ }
134
+ capabilities.workspace = {
135
+ workspaceFolders: {
136
+ supported: true,
137
+ changeNotifications: true,
138
+ },
139
+ };
140
+ }
141
+ else if (params.rootUri) {
142
+ workspaceFolders = [
143
+ {
144
+ name: "<root>",
145
+ uri: params.rootUri,
146
+ path: ensureTrailingDirectorySeparator(await fileURLToRealPath(params.rootUri)),
147
+ },
148
+ ];
149
+ }
150
+ else if (params.rootPath) {
151
+ workspaceFolders = [
152
+ {
153
+ name: "<root>",
154
+ uri: compilerHost.pathToFileURL(params.rootPath),
155
+ path: ensureTrailingDirectorySeparator(await getNormalizedRealPath(compilerHost, params.rootPath)),
156
+ },
157
+ ];
158
+ }
159
+ log("Workspace Folders", workspaceFolders);
160
+ return { capabilities };
161
+ }
162
+ function initialized(params) {
163
+ isInitialized = true;
164
+ log("Initialization complete.");
165
+ }
166
+ async function workspaceFoldersChanged(e) {
167
+ log("Workspace Folders Changed", e);
168
+ const map = new Map(workspaceFolders.map((f) => [f.uri, f]));
169
+ for (const folder of e.removed) {
170
+ map.delete(folder.uri);
171
+ }
172
+ for (const folder of e.added) {
173
+ map.set(folder.uri, {
174
+ ...folder,
175
+ path: ensureTrailingDirectorySeparator(await fileURLToRealPath(folder.uri)),
176
+ });
177
+ }
178
+ workspaceFolders = Array.from(map.values());
179
+ log("Workspace Folders", workspaceFolders);
180
+ }
181
+ function watchedFilesChanged(params) {
182
+ fileSystemCache.notify(params.changes);
183
+ }
184
+ async function compile(document, callback) {
185
+ const path = await getPath(document);
186
+ const mainFile = await getMainFileForDocument(path);
187
+ const config = await getConfig(mainFile, path);
188
+ const options = {
189
+ ...serverOptions,
190
+ emit: config.emit,
191
+ options: config.options,
192
+ };
193
+ if (!upToDate(document)) {
194
+ return undefined;
195
+ }
196
+ let program;
197
+ try {
198
+ program = await compileProgram(compilerHost, mainFile, options, oldPrograms.get(mainFile));
199
+ oldPrograms.set(mainFile, program);
200
+ if (!upToDate(document)) {
201
+ return undefined;
202
+ }
203
+ if (mainFile !== path && !program.sourceFiles.has(path)) {
204
+ // If the file that changed wasn't imported by anything from the main
205
+ // file, retry using the file itself as the main file.
206
+ program = await compileProgram(compilerHost, path, options, oldPrograms.get(path));
207
+ oldPrograms.set(path, program);
208
+ }
209
+ if (!upToDate(document)) {
210
+ return undefined;
211
+ }
212
+ if (callback) {
213
+ const doc = "version" in document ? document : host.getOpenDocumentByURL(document.uri);
214
+ compilerAssert(doc, "Failed to get document.");
215
+ const path = await getPath(doc);
216
+ const script = program.sourceFiles.get(path);
217
+ compilerAssert(script, "Failed to get script.");
218
+ return await callback(program, doc, script);
219
+ }
220
+ return program;
221
+ }
222
+ catch (err) {
223
+ if (host.throwInternalErrors) {
224
+ throw err;
225
+ }
226
+ host.sendDiagnostics({
227
+ uri: document.uri,
228
+ diagnostics: [
229
+ {
230
+ severity: DiagnosticSeverity.Error,
231
+ range: Range.create(0, 0, 0, 0),
232
+ message: `Internal compiler error!\nFile issue at https://github.com/microsoft/typespec\n\n` +
233
+ err.stack,
234
+ },
235
+ ],
236
+ });
237
+ return undefined;
238
+ }
239
+ }
240
+ async function getConfig(mainFile, path) {
241
+ const configPath = await findTypeSpecConfigPath(compilerHost, mainFile);
242
+ if (!configPath) {
243
+ return { ...defaultConfig, projectRoot: getDirectoryPath(mainFile) };
244
+ }
245
+ const cached = await fileSystemCache.get(configPath);
246
+ if (cached === null || cached === void 0 ? void 0 : cached.data) {
247
+ return cached.data;
248
+ }
249
+ const config = await loadTypeSpecConfigFile(compilerHost, configPath);
250
+ await fileSystemCache.setData(configPath, config);
251
+ return config;
252
+ }
253
+ async function getScript(document) {
254
+ var _a;
255
+ const file = await compilerHost.readFile(await getPath(document));
256
+ const cached = (_a = compilerHost.parseCache) === null || _a === void 0 ? void 0 : _a.get(file);
257
+ return cached !== null && cached !== void 0 ? cached : (await compile(document, (_, __, script) => script));
258
+ }
259
+ async function getFoldingRanges(params) {
260
+ const ast = await getScript(params.textDocument);
261
+ if (!ast) {
262
+ return [];
263
+ }
264
+ const file = ast.file;
265
+ const ranges = [];
266
+ let rangeStartSingleLines = -1;
267
+ for (let i = 0; i < ast.comments.length; i++) {
268
+ const comment = ast.comments[i];
269
+ if (comment.kind === SyntaxKind.LineComment &&
270
+ i + 1 < ast.comments.length &&
271
+ ast.comments[i + 1].kind === SyntaxKind.LineComment &&
272
+ ast.comments[i + 1].pos === skipWhiteSpace(file.text, comment.end)) {
273
+ if (rangeStartSingleLines === -1) {
274
+ rangeStartSingleLines = comment.pos;
275
+ }
276
+ }
277
+ else if (rangeStartSingleLines !== -1) {
278
+ addRange(rangeStartSingleLines, comment.end);
279
+ rangeStartSingleLines = -1;
280
+ }
281
+ else {
282
+ addRange(comment.pos, comment.end);
283
+ }
284
+ }
285
+ visitChildren(ast, addRangesForNode);
286
+ function addRangesForNode(node) {
287
+ if (node.kind === SyntaxKind.Doc) {
288
+ return; // fold doc comments as regular comments
289
+ }
290
+ let nodeStart = node.pos;
291
+ if ("decorators" in node && node.decorators.length > 0) {
292
+ const decoratorEnd = node.decorators[node.decorators.length - 1].end;
293
+ addRange(nodeStart, decoratorEnd);
294
+ nodeStart = skipTrivia(file.text, decoratorEnd);
295
+ }
296
+ addRange(nodeStart, node.end);
297
+ visitChildren(node, addRangesForNode);
298
+ }
299
+ return ranges;
300
+ function addRange(startPos, endPos) {
301
+ const start = file.getLineAndCharacterOfPosition(startPos);
302
+ const end = file.getLineAndCharacterOfPosition(endPos);
303
+ if (start.line !== end.line) {
304
+ ranges.push({
305
+ startLine: start.line,
306
+ startCharacter: start.character,
307
+ endLine: end.line,
308
+ endCharacter: end.character,
309
+ });
310
+ }
311
+ }
312
+ }
313
+ async function getDocumentSymbols(params) {
314
+ const ast = await getScript(params.textDocument);
315
+ if (!ast) {
316
+ return [];
317
+ }
318
+ return getSymbolStructure(ast);
319
+ }
320
+ async function findDocumentHighlight(params) {
321
+ let highlights = [];
322
+ await compile(params.textDocument, (program, document, file) => {
323
+ const identifiers = findReferenceIdentifiers(program, file, document.offsetAt(params.position), [file]);
324
+ highlights = identifiers.map((identifier) => ({
325
+ range: getRange(identifier, file.file),
326
+ kind: DocumentHighlightKind.Read,
327
+ }));
328
+ });
329
+ return highlights;
330
+ }
331
+ async function checkChange(change) {
332
+ var _a, _b, _c;
333
+ const program = await compile(change.document);
334
+ if (!program) {
335
+ return;
336
+ }
337
+ // Group diagnostics by file.
338
+ //
339
+ // Initialize diagnostics for all source files in program to empty array
340
+ // as we must send an empty array when a file has no diagnostics or else
341
+ // stale diagnostics from a previous run will stick around in the IDE.
342
+ //
343
+ const diagnosticMap = new Map();
344
+ diagnosticMap.set(change.document, []);
345
+ for (const each of program.sourceFiles.values()) {
346
+ const document = (_a = each.file) === null || _a === void 0 ? void 0 : _a.document;
347
+ if (document) {
348
+ diagnosticMap.set(document, []);
349
+ }
350
+ }
351
+ for (const each of program.diagnostics) {
352
+ let document;
353
+ const location = getSourceLocation(each.target);
354
+ if (location === null || location === void 0 ? void 0 : location.file) {
355
+ document = location.file.document;
356
+ }
357
+ else {
358
+ // https://github.com/Microsoft/language-server-protocol/issues/256
359
+ //
360
+ // LSP does not currently allow sending a diagnostic with no location so
361
+ // we report diagnostics with no location on the document that changed to
362
+ // trigger.
363
+ document = change.document;
364
+ }
365
+ if (!document || !upToDate(document)) {
366
+ continue;
367
+ }
368
+ const start = document.positionAt((_b = location === null || location === void 0 ? void 0 : location.pos) !== null && _b !== void 0 ? _b : 0);
369
+ const end = document.positionAt((_c = location === null || location === void 0 ? void 0 : location.end) !== null && _c !== void 0 ? _c : 0);
370
+ const range = Range.create(start, end);
371
+ const severity = convertSeverity(each.severity);
372
+ const diagnostic = VSDiagnostic.create(range, each.message, severity, each.code, "TypeSpec");
373
+ if (each.code === "deprecated") {
374
+ diagnostic.tags = [DiagnosticTag.Deprecated];
375
+ }
376
+ const diagnostics = diagnosticMap.get(document);
377
+ compilerAssert(diagnostics, "Diagnostic reported against a source file that was not added to the program.");
378
+ diagnostics.push(diagnostic);
379
+ }
380
+ for (const [document, diagnostics] of diagnosticMap) {
381
+ sendDiagnostics(document, diagnostics);
382
+ }
383
+ }
384
+ async function getHover(params) {
385
+ const docString = await compile(params.textDocument, (program, document, file) => {
386
+ var _a;
387
+ const id = getNodeAtPosition(file, document.offsetAt(params.position));
388
+ const sym = (id === null || id === void 0 ? void 0 : id.kind) === SyntaxKind.Identifier ? program.checker.resolveIdentifier(id) : undefined;
389
+ if (sym) {
390
+ const type = (_a = sym.type) !== null && _a !== void 0 ? _a : program.checker.getTypeForNode(sym.declarations[0]);
391
+ return getTypeDetails(program, type);
392
+ }
393
+ return undefined;
394
+ });
395
+ const markdown = {
396
+ kind: MarkupKind.Markdown,
397
+ value: docString !== null && docString !== void 0 ? docString : "",
398
+ };
399
+ return {
400
+ contents: markdown,
401
+ };
402
+ }
403
+ async function getSignatureHelp(params) {
404
+ return await compile(params.textDocument, (program, document, file) => {
405
+ const nodeAtPosition = getNodeAtPosition(file, document.offsetAt(params.position));
406
+ const data = nodeAtPosition && findDecoratorOrParameter(nodeAtPosition);
407
+ if (data === undefined) {
408
+ return undefined;
409
+ }
410
+ const { node, argumentIndex } = data;
411
+ const sym = program.checker.resolveIdentifier(node.target.kind === SyntaxKind.MemberExpression ? node.target.id : node.target);
412
+ const decoratorDeclNode = sym === null || sym === void 0 ? void 0 : sym.declarations.find((x) => x.kind === SyntaxKind.DecoratorDeclarationStatement);
413
+ if (decoratorDeclNode === undefined) {
414
+ return undefined;
415
+ }
416
+ const type = program.checker.getTypeForNode(decoratorDeclNode);
417
+ compilerAssert(type.kind === "Decorator", "Expected type to be a decorator.");
418
+ const parameterDocs = getParameterDocumentation(program, type);
419
+ let labelPrefix = "";
420
+ const parameters = [];
421
+ if (node.kind === SyntaxKind.AugmentDecoratorStatement) {
422
+ const targetType = decoratorDeclNode.target.type
423
+ ? program.checker.getTypeForNode(decoratorDeclNode.target.type)
424
+ : undefined;
425
+ parameters.push({
426
+ label: `${decoratorDeclNode.target.id.sv}: ${targetType ? getTypeName(targetType) : "unknown"}`,
427
+ });
428
+ labelPrefix = "@";
429
+ }
430
+ parameters.push(...type.parameters.map((x) => {
431
+ const info = {
432
+ // prettier-ignore
433
+ label: `${x.rest ? "..." : ""}${x.name}${x.optional ? "?" : ""}: ${getTypeName(x.type)}`,
434
+ };
435
+ const doc = parameterDocs.get(x.name);
436
+ if (doc) {
437
+ info.documentation = { kind: MarkupKind.Markdown, value: doc };
438
+ }
439
+ return info;
440
+ }));
441
+ const help = {
442
+ signatures: [
443
+ {
444
+ label: `${labelPrefix}${type.name}(${parameters.map((x) => x.label).join(", ")})`,
445
+ parameters,
446
+ activeParameter: Math.min(parameters.length - 1, argumentIndex),
447
+ },
448
+ ],
449
+ activeSignature: 0,
450
+ activeParameter: 0,
451
+ };
452
+ const doc = getTypeDetails(program, type, {
453
+ includeSignature: false,
454
+ includeParameterTags: false,
455
+ });
456
+ if (doc) {
457
+ help.signatures[0].documentation = { kind: MarkupKind.Markdown, value: doc };
458
+ }
459
+ return help;
460
+ });
461
+ }
462
+ async function formatDocument(params) {
463
+ const document = host.getOpenDocumentByURL(params.textDocument.uri);
464
+ if (document === undefined) {
465
+ return [];
466
+ }
467
+ const formattedText = formatTypeSpec(document.getText(), {
468
+ tabWidth: params.options.tabSize,
469
+ useTabs: !params.options.insertSpaces,
470
+ });
471
+ return [minimalEdit(document, formattedText)];
472
+ }
473
+ function minimalEdit(document, string1) {
474
+ const string0 = document.getText();
475
+ // length of common prefix
476
+ let i = 0;
477
+ while (i < string0.length && i < string1.length && string0[i] === string1[i]) {
478
+ ++i;
479
+ }
480
+ // length of common suffix
481
+ let j = 0;
482
+ while (i + j < string0.length &&
483
+ i + j < string1.length &&
484
+ string0[string0.length - j - 1] === string1[string1.length - j - 1]) {
485
+ ++j;
486
+ }
487
+ const newText = string1.substring(i, string1.length - j);
488
+ const pos0 = document.positionAt(i);
489
+ const pos1 = document.positionAt(string0.length - j);
490
+ return TextEdit.replace(Range.create(pos0, pos1), newText);
491
+ }
492
+ async function gotoDefinition(params) {
493
+ const sym = await compile(params.textDocument, (program, document, file) => {
494
+ const id = getNodeAtPosition(file, document.offsetAt(params.position));
495
+ return (id === null || id === void 0 ? void 0 : id.kind) === SyntaxKind.Identifier ? program.checker.resolveIdentifier(id) : undefined;
496
+ });
497
+ return getLocations(sym === null || sym === void 0 ? void 0 : sym.declarations);
498
+ }
499
+ async function complete(params) {
500
+ const completions = {
501
+ isIncomplete: false,
502
+ items: [],
503
+ };
504
+ await compile(params.textDocument, async (program, document, file) => {
505
+ const node = getCompletionNodeAtPosition(file, document.offsetAt(params.position));
506
+ await resolveCompletion({
507
+ program,
508
+ file,
509
+ completions,
510
+ params,
511
+ }, node);
512
+ });
513
+ return completions;
514
+ }
515
+ async function findReferences(params) {
516
+ const identifiers = await compile(params.textDocument, (program, document, file) => findReferenceIdentifiers(program, file, document.offsetAt(params.position)));
517
+ return getLocations(identifiers);
518
+ }
519
+ async function prepareRename(params) {
520
+ return await compile(params.textDocument, (_, document, file) => {
521
+ var _a;
522
+ const id = getNodeAtPosition(file, document.offsetAt(params.position));
523
+ return (id === null || id === void 0 ? void 0 : id.kind) === SyntaxKind.Identifier ? (_a = getLocation(id)) === null || _a === void 0 ? void 0 : _a.range : undefined;
524
+ });
525
+ }
526
+ async function rename(params) {
527
+ const changes = {};
528
+ await compile(params.textDocument, (program, document, file) => {
529
+ const identifiers = findReferenceIdentifiers(program, file, document.offsetAt(params.position));
530
+ for (const id of identifiers) {
531
+ const location = getLocation(id);
532
+ if (!location) {
533
+ continue;
534
+ }
535
+ const change = TextEdit.replace(location.range, params.newName);
536
+ if (location.uri in changes) {
537
+ changes[location.uri].push(change);
538
+ }
539
+ else {
540
+ changes[location.uri] = [change];
541
+ }
542
+ }
543
+ });
544
+ return { changes };
545
+ }
546
+ function findReferenceIdentifiers(program, file, pos, searchFiles = program.sourceFiles.values()) {
547
+ const id = getNodeAtPosition(file, pos);
548
+ if ((id === null || id === void 0 ? void 0 : id.kind) !== SyntaxKind.Identifier) {
549
+ return [];
550
+ }
551
+ const sym = program.checker.resolveIdentifier(id);
552
+ if (!sym) {
553
+ return [id];
554
+ }
555
+ const references = [];
556
+ for (const searchFile of searchFiles) {
557
+ visitChildren(searchFile, function visit(node) {
558
+ if (node.kind === SyntaxKind.Identifier) {
559
+ const s = program.checker.resolveIdentifier(node);
560
+ if (s === sym || (sym.type && (s === null || s === void 0 ? void 0 : s.type) === sym.type)) {
561
+ references.push(node);
562
+ }
563
+ }
564
+ visitChildren(node, visit);
565
+ });
566
+ }
567
+ return references;
568
+ }
569
+ async function getSemanticTokens(params) {
570
+ const ignore = -1;
571
+ const defer = -2;
572
+ const ast = await getScript(params.textDocument);
573
+ if (!ast) {
574
+ return [];
575
+ }
576
+ const file = ast.file;
577
+ const tokens = mapTokens();
578
+ classifyNode(ast);
579
+ return Array.from(tokens.values()).filter((t) => t.kind !== undefined);
580
+ function mapTokens() {
581
+ const tokens = new Map();
582
+ const scanner = createScanner(file, () => { });
583
+ while (scanner.scan() !== Token.EndOfFile) {
584
+ const kind = classifyToken(scanner.token);
585
+ if (kind === ignore) {
586
+ continue;
587
+ }
588
+ tokens.set(scanner.tokenPosition, {
589
+ kind: kind === defer ? undefined : kind,
590
+ pos: scanner.tokenPosition,
591
+ end: scanner.position,
592
+ });
593
+ }
594
+ return tokens;
595
+ }
596
+ function classifyToken(token) {
597
+ switch (token) {
598
+ case Token.Identifier:
599
+ return defer;
600
+ case Token.StringLiteral:
601
+ return SemanticTokenKind.String;
602
+ case Token.NumericLiteral:
603
+ return SemanticTokenKind.Number;
604
+ case Token.MultiLineComment:
605
+ case Token.SingleLineComment:
606
+ return SemanticTokenKind.Comment;
607
+ default:
608
+ if (isKeyword(token)) {
609
+ return SemanticTokenKind.Keyword;
610
+ }
611
+ if (isPunctuation(token)) {
612
+ return SemanticTokenKind.Operator;
613
+ }
614
+ return ignore;
615
+ }
616
+ }
617
+ function classifyNode(node) {
618
+ switch (node.kind) {
619
+ case SyntaxKind.DirectiveExpression:
620
+ classify(node.target, SemanticTokenKind.Keyword);
621
+ break;
622
+ case SyntaxKind.TemplateParameterDeclaration:
623
+ classify(node.id, SemanticTokenKind.TypeParameter);
624
+ break;
625
+ case SyntaxKind.ModelProperty:
626
+ case SyntaxKind.UnionVariant:
627
+ classify(node.id, SemanticTokenKind.Property);
628
+ break;
629
+ case SyntaxKind.AliasStatement:
630
+ classify(node.id, SemanticTokenKind.Struct);
631
+ break;
632
+ case SyntaxKind.ModelStatement:
633
+ classify(node.id, SemanticTokenKind.Struct);
634
+ break;
635
+ case SyntaxKind.ScalarStatement:
636
+ classify(node.id, SemanticTokenKind.Type);
637
+ break;
638
+ case SyntaxKind.EnumStatement:
639
+ classify(node.id, SemanticTokenKind.Enum);
640
+ break;
641
+ case SyntaxKind.EnumMember:
642
+ classify(node.id, SemanticTokenKind.EnumMember);
643
+ break;
644
+ case SyntaxKind.NamespaceStatement:
645
+ classify(node.id, SemanticTokenKind.Namespace);
646
+ break;
647
+ case SyntaxKind.InterfaceStatement:
648
+ classify(node.id, SemanticTokenKind.Interface);
649
+ break;
650
+ case SyntaxKind.OperationStatement:
651
+ classify(node.id, SemanticTokenKind.Function);
652
+ break;
653
+ case SyntaxKind.DecoratorDeclarationStatement:
654
+ classify(node.id, SemanticTokenKind.Function);
655
+ break;
656
+ case SyntaxKind.FunctionDeclarationStatement:
657
+ classify(node.id, SemanticTokenKind.Function);
658
+ break;
659
+ case SyntaxKind.FunctionParameter:
660
+ classify(node.id, SemanticTokenKind.Parameter);
661
+ break;
662
+ case SyntaxKind.AugmentDecoratorStatement:
663
+ classifyReference(node.targetType, SemanticTokenKind.Type);
664
+ classifyReference(node.target, SemanticTokenKind.Macro);
665
+ break;
666
+ case SyntaxKind.DecoratorExpression:
667
+ classifyReference(node.target, SemanticTokenKind.Macro);
668
+ break;
669
+ case SyntaxKind.TypeReference:
670
+ classifyReference(node.target);
671
+ break;
672
+ case SyntaxKind.MemberExpression:
673
+ classifyReference(node);
674
+ break;
675
+ case SyntaxKind.ProjectionStatement:
676
+ classifyReference(node.selector);
677
+ classify(node.id, SemanticTokenKind.Variable);
678
+ break;
679
+ case SyntaxKind.Projection:
680
+ classify(node.directionId, SemanticTokenKind.Keyword);
681
+ break;
682
+ case SyntaxKind.ProjectionParameterDeclaration:
683
+ classifyReference(node.id, SemanticTokenKind.Parameter);
684
+ break;
685
+ case SyntaxKind.ProjectionCallExpression:
686
+ classifyReference(node.target, SemanticTokenKind.Function);
687
+ for (const arg of node.arguments) {
688
+ classifyReference(arg);
689
+ }
690
+ break;
691
+ case SyntaxKind.ProjectionMemberExpression:
692
+ classifyReference(node.id);
693
+ break;
694
+ }
695
+ visitChildren(node, classifyNode);
696
+ }
697
+ function classify(node, kind) {
698
+ const token = tokens.get(node.pos);
699
+ if (token && token.kind === undefined) {
700
+ token.kind = kind;
701
+ }
702
+ }
703
+ function classifyReference(node, kind = SemanticTokenKind.Type) {
704
+ switch (node.kind) {
705
+ case SyntaxKind.MemberExpression:
706
+ classifyIdentifier(node.base, SemanticTokenKind.Namespace);
707
+ classifyIdentifier(node.id, kind);
708
+ break;
709
+ case SyntaxKind.ProjectionMemberExpression:
710
+ classifyReference(node.base, SemanticTokenKind.Namespace);
711
+ classifyIdentifier(node.id, kind);
712
+ break;
713
+ case SyntaxKind.TypeReference:
714
+ classifyIdentifier(node.target, kind);
715
+ break;
716
+ case SyntaxKind.Identifier:
717
+ classify(node, kind);
718
+ break;
719
+ }
720
+ }
721
+ function classifyIdentifier(node, kind) {
722
+ if (node.kind === SyntaxKind.Identifier) {
723
+ classify(node, kind);
724
+ }
725
+ }
726
+ }
727
+ async function buildSemanticTokens(params) {
728
+ const builder = new SemanticTokensBuilder();
729
+ const tokens = await getSemanticTokens(params);
730
+ const file = await compilerHost.readFile(await getPath(params.textDocument));
731
+ const starts = file.getLineStarts();
732
+ for (const token of tokens) {
733
+ const start = file.getLineAndCharacterOfPosition(token.pos);
734
+ const end = file.getLineAndCharacterOfPosition(token.end);
735
+ for (let pos = token.pos, line = start.line; line <= end.line; line++) {
736
+ const endPos = line === end.line ? token.end : starts[line + 1];
737
+ const character = line === start.line ? start.character : 0;
738
+ builder.push(line, character, endPos - pos, token.kind, 0);
739
+ pos = endPos;
740
+ }
741
+ }
742
+ return builder.build();
743
+ }
744
+ function documentClosed(change) {
745
+ // clear diagnostics on file close
746
+ sendDiagnostics(change.document, []);
747
+ }
748
+ function getLocations(targets) {
749
+ var _a;
750
+ return (_a = targets === null || targets === void 0 ? void 0 : targets.map(getLocation).filter((x) => !!x)) !== null && _a !== void 0 ? _a : [];
751
+ }
752
+ function getLocation(target) {
753
+ const location = getSourceLocation(target);
754
+ if (location.isSynthetic) {
755
+ return undefined;
756
+ }
757
+ return {
758
+ uri: getURL(location.file.path),
759
+ range: getRange(location, location.file),
760
+ };
761
+ }
762
+ function getRange(location, file) {
763
+ const start = file.getLineAndCharacterOfPosition(location.pos);
764
+ const end = file.getLineAndCharacterOfPosition(location.end);
765
+ return Range.create(start, end);
766
+ }
767
+ function convertSeverity(severity) {
768
+ switch (severity) {
769
+ case "warning":
770
+ return DiagnosticSeverity.Warning;
771
+ case "error":
772
+ return DiagnosticSeverity.Error;
773
+ }
774
+ }
775
+ function log(message, details = undefined) {
776
+ message = `[${new Date().toLocaleTimeString()}] ${message}`;
777
+ if (details) {
778
+ message += ": " + JSON.stringify(details, undefined, 2);
779
+ }
780
+ if (!isInitialized) {
781
+ pendingMessages.push(message);
782
+ return;
783
+ }
784
+ for (const pending of pendingMessages) {
785
+ host.log(pending);
786
+ }
787
+ pendingMessages = [];
788
+ host.log(message);
789
+ }
790
+ function sendDiagnostics(document, diagnostics) {
791
+ host.sendDiagnostics({
792
+ uri: document.uri,
793
+ version: document.version,
794
+ diagnostics,
795
+ });
796
+ }
797
+ /**
798
+ * Determine if the given document is the latest version.
799
+ *
800
+ * A document can become out-of-date if a change comes in during an async
801
+ * operation.
802
+ */
803
+ function upToDate(document) {
804
+ var _a;
805
+ if (!("version" in document)) {
806
+ return true;
807
+ }
808
+ return document.version === ((_a = host.getOpenDocumentByURL(document.uri)) === null || _a === void 0 ? void 0 : _a.version);
809
+ }
810
+ /**
811
+ * Infer the appropriate entry point (a.k.a. "main file") for analyzing a
812
+ * change to the file at the given path. This is necessary because different
813
+ * results can be obtained from compiling the same file with different entry
814
+ * points.
815
+ *
816
+ * Walk directory structure upwards looking for package.json with tspMain or
817
+ * main.tsp file. Stop search when reaching a workspace root. If a root is
818
+ * reached without finding an entry point, use the given path as its own
819
+ * entry point.
820
+ *
821
+ * Untitled documents are always treated as their own entry points as they
822
+ * do not exist in a directory that could pull them in via another entry
823
+ * point.
824
+ */
825
+ async function getMainFileForDocument(path) {
826
+ if (path.startsWith("untitled:")) {
827
+ return path;
828
+ }
829
+ let dir = getDirectoryPath(path);
830
+ const options = { allowFileNotFound: true };
831
+ while (inWorkspace(dir)) {
832
+ let mainFile = "main.tsp";
833
+ let pkg;
834
+ const pkgPath = joinPaths(dir, "package.json");
835
+ const cached = await fileSystemCache.get(pkgPath);
836
+ if (cached) {
837
+ pkg = cached.data;
838
+ }
839
+ else {
840
+ [pkg] = await loadFile(compilerHost, pkgPath, JSON.parse, logMainFileSearchDiagnostic, options);
841
+ await fileSystemCache.setData(pkgPath, pkg !== null && pkg !== void 0 ? pkg : {});
842
+ }
843
+ const tspMain = resolveTspMain(pkg);
844
+ if (typeof tspMain === "string") {
845
+ mainFile = tspMain;
846
+ }
847
+ const candidate = joinPaths(dir, mainFile);
848
+ const stat = await doIO(() => compilerHost.stat(candidate), candidate, logMainFileSearchDiagnostic, options);
849
+ if (stat === null || stat === void 0 ? void 0 : stat.isFile()) {
850
+ return candidate;
851
+ }
852
+ const parentDir = getDirectoryPath(dir);
853
+ if (parentDir === dir) {
854
+ break;
855
+ }
856
+ dir = parentDir;
857
+ }
858
+ return path;
859
+ function logMainFileSearchDiagnostic(diagnostic) {
860
+ log(`Unexpected diagnostic while looking for main file of ${path}`, formatDiagnostic(diagnostic));
861
+ }
862
+ }
863
+ function inWorkspace(path) {
864
+ path = ensureTrailingDirectorySeparator(path);
865
+ return workspaceFolders.some((f) => path.startsWith(f.path));
866
+ }
867
+ async function getPath(document) {
868
+ if (isUntitled(document.uri)) {
869
+ return document.uri;
870
+ }
871
+ const path = await fileURLToRealPath(document.uri);
872
+ pathToURLMap.set(path, document.uri);
873
+ return path;
874
+ }
875
+ function getURL(path) {
876
+ var _a;
877
+ if (isUntitled(path)) {
878
+ return path;
879
+ }
880
+ return (_a = pathToURLMap.get(path)) !== null && _a !== void 0 ? _a : compilerHost.pathToFileURL(path);
881
+ }
882
+ function isUntitled(pathOrUrl) {
883
+ return pathOrUrl.startsWith("untitled:");
884
+ }
885
+ function getOpenDocument(path) {
886
+ const url = getURL(path);
887
+ return url ? host.getOpenDocumentByURL(url) : undefined;
888
+ }
889
+ async function fileURLToRealPath(url) {
890
+ return getNormalizedRealPath(compilerHost, compilerHost.fileURLToPath(url));
891
+ }
892
+ function createFileSystemCache() {
893
+ const cache = new Map();
894
+ let changes = [];
895
+ return {
896
+ async get(path) {
897
+ for (const change of changes) {
898
+ const path = await fileURLToRealPath(change.uri);
899
+ cache.delete(path);
900
+ }
901
+ changes = [];
902
+ return cache.get(path);
903
+ },
904
+ set(path, entry) {
905
+ cache.set(path, entry);
906
+ },
907
+ async setData(path, data) {
908
+ const entry = await this.get(path);
909
+ if (entry) {
910
+ entry.data = data;
911
+ }
912
+ },
913
+ notify(changes) {
914
+ changes.push(...changes);
915
+ },
916
+ };
917
+ }
918
+ function createCompilerHost() {
919
+ const base = host.compilerHost;
920
+ return {
921
+ ...base,
922
+ parseCache: new WeakMap(),
923
+ readFile,
924
+ stat,
925
+ getSourceFileKind,
926
+ };
927
+ async function readFile(path) {
928
+ const document = getOpenDocument(path);
929
+ const cached = await fileSystemCache.get(path);
930
+ // Try cache
931
+ if (cached && (!document || document.version === cached.version)) {
932
+ if (cached.type === "error") {
933
+ throw cached.error;
934
+ }
935
+ return cached.file;
936
+ }
937
+ // Try open document, although this is cheap, the instance still needs
938
+ // to be cached so that the compiler can reuse parse and bind results.
939
+ if (document) {
940
+ const file = {
941
+ document,
942
+ ...createSourceFile(document.getText(), path),
943
+ };
944
+ fileSystemCache.set(path, { type: "file", file, version: document.version });
945
+ return file;
946
+ }
947
+ // Hit the disk and cache
948
+ try {
949
+ const file = await base.readFile(path);
950
+ fileSystemCache.set(path, { type: "file", file });
951
+ return file;
952
+ }
953
+ catch (error) {
954
+ fileSystemCache.set(path, { type: "error", error });
955
+ throw error;
956
+ }
957
+ }
958
+ async function stat(path) {
959
+ var _a;
960
+ // if we have an open document for the path or a cache entry, then we know
961
+ // it's a file and not a directory and needn't hit the disk.
962
+ if (getOpenDocument(path) || ((_a = (await fileSystemCache.get(path))) === null || _a === void 0 ? void 0 : _a.type) === "file") {
963
+ return {
964
+ isFile() {
965
+ return true;
966
+ },
967
+ isDirectory() {
968
+ return false;
969
+ },
970
+ };
971
+ }
972
+ return await base.stat(path);
973
+ }
974
+ function getSourceFileKind(path) {
975
+ const document = getOpenDocument(path);
976
+ if ((document === null || document === void 0 ? void 0 : document.languageId) === "typespec") {
977
+ return "typespec";
978
+ }
979
+ return getSourceFileKindFromExt(path);
980
+ }
981
+ }
982
+ }
983
+ function findDecoratorOrParameter(node) {
984
+ var _a, _b, _c;
985
+ if (node.kind === SyntaxKind.DecoratorExpression) {
986
+ return { node, argumentIndex: node.arguments.length };
987
+ }
988
+ if (node.kind === SyntaxKind.AugmentDecoratorStatement) {
989
+ return { node, argumentIndex: node.arguments.length + 1 };
990
+ }
991
+ let current = node;
992
+ while (current) {
993
+ if (((_a = current.parent) === null || _a === void 0 ? void 0 : _a.kind) === SyntaxKind.DecoratorExpression) {
994
+ return {
995
+ node: current.parent,
996
+ argumentIndex: current.parent.arguments.indexOf(current),
997
+ };
998
+ }
999
+ if (((_b = current.parent) === null || _b === void 0 ? void 0 : _b.kind) === SyntaxKind.AugmentDecoratorStatement) {
1000
+ return {
1001
+ node: current.parent,
1002
+ argumentIndex: current === ((_c = current.parent) === null || _c === void 0 ? void 0 : _c.targetType)
1003
+ ? 0
1004
+ : current.parent.arguments.indexOf(current) + 1,
1005
+ };
1006
+ }
1007
+ current = current.parent;
1008
+ }
1009
+ return undefined;
1010
+ }
1011
+ /**
1012
+ * Resolve the node that should be auto completed at the given position.
1013
+ * It will try to guess what node it could be as during auto complete the ast might not be complete.
1014
+ * @internal
1015
+ */
1016
+ export function getCompletionNodeAtPosition(script, position, filter = (node) => true) {
1017
+ const realNode = getNodeAtPosition(script, position, filter);
1018
+ if ((realNode === null || realNode === void 0 ? void 0 : realNode.kind) === SyntaxKind.StringLiteral) {
1019
+ return realNode;
1020
+ }
1021
+ // If we're not immediately after an identifier character, then advance
1022
+ // the position past any trivia. This is done because a zero-width
1023
+ // inserted missing identifier that the user is now trying to complete
1024
+ // starts after the trivia following the cursor.
1025
+ const cp = codePointBefore(script.file.text, position);
1026
+ if (!cp || !isIdentifierContinue(cp)) {
1027
+ const newPosition = skipTrivia(script.file.text, position);
1028
+ if (newPosition !== position) {
1029
+ return getNodeAtPosition(script, newPosition, filter);
1030
+ }
1031
+ }
1032
+ return realNode;
1033
+ }
1034
+ //# sourceMappingURL=serverlib.js.map