@hydranium/core 1.0.0-next.4 → 1.0.0-next.40

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 (228) hide show
  1. package/lib/documents/ast-document-manager.d.ts +42 -5
  2. package/lib/documents/ast-document-manager.d.ts.map +1 -1
  3. package/lib/documents/ast-document-manager.js +9 -12
  4. package/lib/documents/ast-document-manager.js.map +1 -1
  5. package/lib/documents/hydranium-text-documents.d.ts.map +1 -1
  6. package/lib/documents/hydranium-text-documents.js +41 -9
  7. package/lib/documents/hydranium-text-documents.js.map +1 -1
  8. package/lib/documents/language-client-text-shadow.d.ts +24 -1
  9. package/lib/documents/language-client-text-shadow.d.ts.map +1 -1
  10. package/lib/documents/language-client-text-shadow.js +36 -2
  11. package/lib/documents/language-client-text-shadow.js.map +1 -1
  12. package/lib/documents/self-save-registry.d.ts +37 -6
  13. package/lib/documents/self-save-registry.d.ts.map +1 -1
  14. package/lib/documents/self-save-registry.js +28 -15
  15. package/lib/documents/self-save-registry.js.map +1 -1
  16. package/lib/index.d.ts +2 -0
  17. package/lib/index.d.ts.map +1 -1
  18. package/lib/index.js +5 -0
  19. package/lib/index.js.map +1 -1
  20. package/lib/langium/ast-extension/ast-node-builder.d.ts +32 -9
  21. package/lib/langium/ast-extension/ast-node-builder.d.ts.map +1 -1
  22. package/lib/langium/ast-extension/ast-node-builder.js +60 -22
  23. package/lib/langium/ast-extension/ast-node-builder.js.map +1 -1
  24. package/lib/langium/bootstrap.d.ts.map +1 -1
  25. package/lib/langium/bootstrap.js +16 -9
  26. package/lib/langium/bootstrap.js.map +1 -1
  27. package/lib/langium/document-builder/build-pipeline-integration.d.ts +13 -1
  28. package/lib/langium/document-builder/build-pipeline-integration.d.ts.map +1 -1
  29. package/lib/langium/document-builder/build-pipeline-integration.js +1 -1
  30. package/lib/langium/document-builder/build-pipeline-integration.js.map +1 -1
  31. package/lib/langium/document-builder/build-session.d.ts +93 -0
  32. package/lib/langium/document-builder/build-session.d.ts.map +1 -0
  33. package/lib/langium/document-builder/build-session.js +72 -0
  34. package/lib/langium/document-builder/build-session.js.map +1 -0
  35. package/lib/langium/document-builder/document-builder.d.ts +150 -7
  36. package/lib/langium/document-builder/document-builder.d.ts.map +1 -1
  37. package/lib/langium/document-builder/document-builder.js +298 -11
  38. package/lib/langium/document-builder/document-builder.js.map +1 -1
  39. package/lib/langium/document-builder/index.d.ts +1 -0
  40. package/lib/langium/document-builder/index.d.ts.map +1 -1
  41. package/lib/langium/document-builder/index.js +1 -0
  42. package/lib/langium/document-builder/index.js.map +1 -1
  43. package/lib/langium/integration-services.d.ts +45 -1
  44. package/lib/langium/integration-services.d.ts.map +1 -1
  45. package/lib/langium/integration-services.js +10 -5
  46. package/lib/langium/integration-services.js.map +1 -1
  47. package/lib/langium/integrity/integrity-service.d.ts +5 -0
  48. package/lib/langium/integrity/integrity-service.d.ts.map +1 -1
  49. package/lib/langium/integrity/integrity-service.js +34 -1
  50. package/lib/langium/integrity/integrity-service.js.map +1 -1
  51. package/lib/langium/keys/containment.d.ts +64 -0
  52. package/lib/langium/keys/containment.d.ts.map +1 -0
  53. package/lib/langium/keys/containment.js +53 -0
  54. package/lib/langium/keys/containment.js.map +1 -0
  55. package/lib/langium/keys/index.d.ts +1 -0
  56. package/lib/langium/keys/index.d.ts.map +1 -1
  57. package/lib/langium/keys/index.js +1 -0
  58. package/lib/langium/keys/index.js.map +1 -1
  59. package/lib/langium/keys/name-based-key-provider.d.ts +4 -0
  60. package/lib/langium/keys/name-based-key-provider.d.ts.map +1 -1
  61. package/lib/langium/keys/name-based-key-provider.js +4 -0
  62. package/lib/langium/keys/name-based-key-provider.js.map +1 -1
  63. package/lib/langium/model-service/model-service.d.ts +103 -7
  64. package/lib/langium/model-service/model-service.d.ts.map +1 -1
  65. package/lib/langium/model-service/model-service.js +70 -89
  66. package/lib/langium/model-service/model-service.js.map +1 -1
  67. package/lib/langium/module.d.ts +82 -13
  68. package/lib/langium/module.d.ts.map +1 -1
  69. package/lib/langium/module.js +21 -12
  70. package/lib/langium/module.js.map +1 -1
  71. package/lib/langium/naming/name-provider.d.ts +10 -0
  72. package/lib/langium/naming/name-provider.d.ts.map +1 -1
  73. package/lib/langium/naming/name-provider.js.map +1 -1
  74. package/lib/langium/naming/name-separator-validation.d.ts +23 -0
  75. package/lib/langium/naming/name-separator-validation.d.ts.map +1 -1
  76. package/lib/langium/naming/name-separator-validation.js +30 -1
  77. package/lib/langium/naming/name-separator-validation.js.map +1 -1
  78. package/lib/langium/residency/cst-residency-service.d.ts +31 -9
  79. package/lib/langium/residency/cst-residency-service.d.ts.map +1 -1
  80. package/lib/langium/residency/cst-residency-service.js +13 -56
  81. package/lib/langium/residency/cst-residency-service.js.map +1 -1
  82. package/lib/langium/scope/hydranium-scope-provider.d.ts +32 -13
  83. package/lib/langium/scope/hydranium-scope-provider.d.ts.map +1 -1
  84. package/lib/langium/scope/hydranium-scope-provider.js +37 -20
  85. package/lib/langium/scope/hydranium-scope-provider.js.map +1 -1
  86. package/lib/langium/shared-services.d.ts +15 -2
  87. package/lib/langium/shared-services.d.ts.map +1 -1
  88. package/lib/langium/shared-services.js.map +1 -1
  89. package/lib/langium/transfer/transfer-encoder.d.ts +33 -2
  90. package/lib/langium/transfer/transfer-encoder.d.ts.map +1 -1
  91. package/lib/langium/transfer/transfer-encoder.js +14 -3
  92. package/lib/langium/transfer/transfer-encoder.js.map +1 -1
  93. package/lib/langium/validation/document-validator.d.ts +145 -6
  94. package/lib/langium/validation/document-validator.d.ts.map +1 -1
  95. package/lib/langium/validation/document-validator.js +211 -4
  96. package/lib/langium/validation/document-validator.js.map +1 -1
  97. package/lib/langium/workspace/document-uri-policy.d.ts +3 -4
  98. package/lib/langium/workspace/document-uri-policy.d.ts.map +1 -1
  99. package/lib/langium/workspace/document-uri-policy.js +3 -4
  100. package/lib/langium/workspace/document-uri-policy.js.map +1 -1
  101. package/lib/langium/workspace/hydranium-langium-document-factory.d.ts +25 -0
  102. package/lib/langium/workspace/hydranium-langium-document-factory.d.ts.map +1 -1
  103. package/lib/langium/workspace/hydranium-langium-document-factory.js +25 -0
  104. package/lib/langium/workspace/hydranium-langium-document-factory.js.map +1 -1
  105. package/lib/langium/workspace/hydranium-workspace-manager.d.ts +21 -1
  106. package/lib/langium/workspace/hydranium-workspace-manager.d.ts.map +1 -1
  107. package/lib/langium/workspace/hydranium-workspace-manager.js +28 -0
  108. package/lib/langium/workspace/hydranium-workspace-manager.js.map +1 -1
  109. package/lib/langium/workspace/in-memory-file-system-provider.d.ts +8 -0
  110. package/lib/langium/workspace/in-memory-file-system-provider.d.ts.map +1 -1
  111. package/lib/langium/workspace/in-memory-file-system-provider.js +11 -2
  112. package/lib/langium/workspace/in-memory-file-system-provider.js.map +1 -1
  113. package/lib/langium/workspace/initialize-workspace.d.ts +22 -2
  114. package/lib/langium/workspace/initialize-workspace.d.ts.map +1 -1
  115. package/lib/langium/workspace/initialize-workspace.js +13 -5
  116. package/lib/langium/workspace/initialize-workspace.js.map +1 -1
  117. package/lib/langium/workspace/langium-documents.d.ts +79 -17
  118. package/lib/langium/workspace/langium-documents.d.ts.map +1 -1
  119. package/lib/langium/workspace/langium-documents.js +83 -28
  120. package/lib/langium/workspace/langium-documents.js.map +1 -1
  121. package/lib/locale/index.d.ts +10 -0
  122. package/lib/locale/index.d.ts.map +1 -0
  123. package/lib/locale/index.js +10 -0
  124. package/lib/locale/index.js.map +1 -0
  125. package/lib/locale/server-locale.d.ts +73 -0
  126. package/lib/locale/server-locale.d.ts.map +1 -0
  127. package/lib/locale/server-locale.js +61 -0
  128. package/lib/locale/server-locale.js.map +1 -0
  129. package/lib/lsp/hydranium-document-update-handler.js +1 -1
  130. package/lib/lsp/hydranium-document-update-handler.js.map +1 -1
  131. package/lib/messages/carriers.d.ts +54 -0
  132. package/lib/messages/carriers.d.ts.map +1 -0
  133. package/lib/messages/carriers.js +62 -0
  134. package/lib/messages/carriers.js.map +1 -0
  135. package/lib/messages/index.d.ts +25 -0
  136. package/lib/messages/index.d.ts.map +1 -0
  137. package/lib/messages/index.js +25 -0
  138. package/lib/messages/index.js.map +1 -0
  139. package/lib/messages/renderer.d.ts +136 -0
  140. package/lib/messages/renderer.d.ts.map +1 -0
  141. package/lib/messages/renderer.js +159 -0
  142. package/lib/messages/renderer.js.map +1 -0
  143. package/lib/node/node-file-system-provider.d.ts.map +1 -1
  144. package/lib/node/node-file-system-provider.js +1 -40
  145. package/lib/node/node-file-system-provider.js.map +1 -1
  146. package/lib/node/rename-over-open-readers.d.ts +52 -0
  147. package/lib/node/rename-over-open-readers.d.ts.map +1 -0
  148. package/lib/node/rename-over-open-readers.js +66 -0
  149. package/lib/node/rename-over-open-readers.js.map +1 -0
  150. package/lib/testing/fake-document.d.ts +14 -3
  151. package/lib/testing/fake-document.d.ts.map +1 -1
  152. package/lib/testing/fake-document.js +18 -3
  153. package/lib/testing/fake-document.js.map +1 -1
  154. package/lib/testing/make-noop-shared-services.d.ts +14 -0
  155. package/lib/testing/make-noop-shared-services.d.ts.map +1 -1
  156. package/lib/testing/make-noop-shared-services.js +28 -2
  157. package/lib/testing/make-noop-shared-services.js.map +1 -1
  158. package/lib/testing/make-test-services.d.ts +31 -4
  159. package/lib/testing/make-test-services.d.ts.map +1 -1
  160. package/lib/testing/make-test-services.js +19 -3
  161. package/lib/testing/make-test-services.js.map +1 -1
  162. package/lib/testing/playwright/server-log-capture.d.ts +14 -4
  163. package/lib/testing/playwright/server-log-capture.d.ts.map +1 -1
  164. package/lib/testing/playwright/server-log-capture.js +21 -4
  165. package/lib/testing/playwright/server-log-capture.js.map +1 -1
  166. package/lib/testing/playwright/server-log-rename-reporter.d.ts.map +1 -1
  167. package/lib/testing/playwright/server-log-rename-reporter.js +10 -1
  168. package/lib/testing/playwright/server-log-rename-reporter.js.map +1 -1
  169. package/lib/testing/stub-ast-document-manager.d.ts +3 -4
  170. package/lib/testing/stub-ast-document-manager.d.ts.map +1 -1
  171. package/lib/testing/stub-ast-document-manager.js +2 -5
  172. package/lib/testing/stub-ast-document-manager.js.map +1 -1
  173. package/lib/testing/stub-document-builder.d.ts +8 -0
  174. package/lib/testing/stub-document-builder.d.ts.map +1 -1
  175. package/lib/testing/stub-document-builder.js +22 -3
  176. package/lib/testing/stub-document-builder.js.map +1 -1
  177. package/lib/testing/stub-model-service.d.ts +1 -1
  178. package/lib/testing/stub-model-service.d.ts.map +1 -1
  179. package/lib/testing/stub-model-service.js +2 -2
  180. package/lib/testing/stub-model-service.js.map +1 -1
  181. package/package.json +17 -8
  182. package/src/documents/ast-document-manager.ts +55 -14
  183. package/src/documents/hydranium-text-documents.ts +41 -9
  184. package/src/documents/language-client-text-shadow.ts +38 -2
  185. package/src/documents/self-save-registry.ts +52 -13
  186. package/src/index.ts +5 -0
  187. package/src/langium/ast-extension/ast-node-builder.ts +66 -22
  188. package/src/langium/bootstrap.ts +16 -9
  189. package/src/langium/document-builder/build-pipeline-integration.ts +14 -1
  190. package/src/langium/document-builder/build-session.ts +87 -0
  191. package/src/langium/document-builder/document-builder.ts +339 -11
  192. package/src/langium/document-builder/index.ts +1 -0
  193. package/src/langium/integration-services.ts +67 -6
  194. package/src/langium/integrity/integrity-service.ts +35 -1
  195. package/src/langium/keys/containment.ts +87 -0
  196. package/src/langium/keys/index.ts +1 -0
  197. package/src/langium/keys/name-based-key-provider.ts +4 -0
  198. package/src/langium/model-service/model-service.ts +145 -22
  199. package/src/langium/module.ts +99 -19
  200. package/src/langium/naming/name-provider.ts +10 -0
  201. package/src/langium/naming/name-separator-validation.ts +34 -5
  202. package/src/langium/residency/cst-residency-service.ts +36 -12
  203. package/src/langium/scope/hydranium-scope-provider.ts +40 -22
  204. package/src/langium/shared-services.ts +19 -2
  205. package/src/langium/transfer/transfer-encoder.ts +45 -3
  206. package/src/langium/validation/document-validator.ts +255 -8
  207. package/src/langium/workspace/document-uri-policy.ts +3 -4
  208. package/src/langium/workspace/hydranium-langium-document-factory.ts +34 -0
  209. package/src/langium/workspace/hydranium-workspace-manager.ts +30 -1
  210. package/src/langium/workspace/in-memory-file-system-provider.ts +13 -3
  211. package/src/langium/workspace/initialize-workspace.ts +34 -5
  212. package/src/langium/workspace/langium-documents.ts +106 -33
  213. package/src/locale/index.ts +10 -0
  214. package/src/locale/server-locale.ts +86 -0
  215. package/src/lsp/hydranium-document-update-handler.ts +1 -1
  216. package/src/messages/carriers.ts +78 -0
  217. package/src/messages/index.ts +27 -0
  218. package/src/messages/renderer.ts +204 -0
  219. package/src/node/node-file-system-provider.ts +1 -41
  220. package/src/node/rename-over-open-readers.ts +78 -0
  221. package/src/testing/fake-document.ts +22 -4
  222. package/src/testing/make-noop-shared-services.ts +50 -2
  223. package/src/testing/make-test-services.ts +49 -7
  224. package/src/testing/playwright/server-log-capture.ts +24 -5
  225. package/src/testing/playwright/server-log-rename-reporter.ts +12 -1
  226. package/src/testing/stub-ast-document-manager.ts +5 -10
  227. package/src/testing/stub-document-builder.ts +32 -3
  228. package/src/testing/stub-model-service.ts +2 -2
@@ -24,9 +24,13 @@ import { type ServerSharedServicesMinimal } from '../shared-services.js';
24
24
  /**
25
25
  * Default priority of the CST-residency pass. Deliberately very high so it runs
26
26
  * *last* among `Validated` build-phase passes (the registry iterates priority
27
- * ascending): every other reaction to the build — an adopter's own derived-state
28
- * pass included — settles while the CST is still guaranteed resident, before the
29
- * residency policy arms the shed.
27
+ * ascending).
28
+ *
29
+ * The ordering is defensive, not load-bearing: the pass only arms or cancels an
30
+ * idle timer, so every pass at `Validated` reads a resident CST whichever order
31
+ * they run in, and lowering it changes nothing observable while that holds. It
32
+ * becomes load-bearing the moment the shed stops being deferred — a pass that
33
+ * frees the CST synchronously has to run after every reader of it.
30
34
  */
31
35
  export const CST_RESIDENCY_PASS_PRIORITY = 1_000_000;
32
36
 
@@ -225,9 +229,29 @@ function rehydrateCst(document: LangiumDocument, factory: LangiumDocumentFactory
225
229
  * demand by the identity-preserving graft of {@link rehydrateNode} /
226
230
  * {@link rehydrate}, driven transparently from the framework
227
231
  * `NameProvider.getNameNode` chokepoint, the comment provider, and
228
- * `AbstractHydraniumLangiumDocuments.getOrCreateDocument`.
232
+ * `HydraniumLangiumDocuments.getOrCreateDocument`.
233
+ */
234
+ /**
235
+ * Keeps a document's CST available to the readers that need one, shedding it
236
+ * for documents that have gone idle and re-grafting on demand.
229
237
  */
230
- export class CstResidencyService {
238
+ export interface CstResidencyService {
239
+ /**
240
+ * Ensure `document` has a CST, re-parsing its retained text if it was shed.
241
+ * A resident document is left exactly as it is, so this is safe to call on
242
+ * a hot path and safe to call twice.
243
+ */
244
+ rehydrate(document: LangiumDocument): void;
245
+
246
+ /**
247
+ * Node-level convenience over {@link rehydrate}, cheap enough for an
248
+ * unconditional call: a node whose `$cstNode` is already set returns
249
+ * without resolving its document.
250
+ */
251
+ rehydrateNode(node: AstNode): void;
252
+ }
253
+
254
+ export class DefaultCstResidencyService implements CstResidencyService {
231
255
  protected readonly strategy: CstResidencyStrategy;
232
256
  /** Bytes-per-node for the optional reclaim estimate in traces; `0` disables it. */
233
257
  protected readonly estimatedBytesPerShedNode: number;
@@ -277,8 +301,8 @@ export class CstResidencyService {
277
301
  * until navigation latency on shed files is actually observed to hurt. This
278
302
  * method is where that hook goes.
279
303
  */
280
- rehydrate(document: LangiumDocument): boolean {
281
- return rehydrateCst(document, this.services.workspace.LangiumDocumentFactory);
304
+ rehydrate(document: LangiumDocument): void {
305
+ rehydrateCst(document, this.services.workspace.LangiumDocumentFactory);
282
306
  }
283
307
 
284
308
  /**
@@ -287,11 +311,11 @@ export class CstResidencyService {
287
311
  * `true` without even resolving the document, so hot read paths
288
312
  * (`getNameNode`, comment lookup) call this unconditionally.
289
313
  */
290
- rehydrateNode(node: AstNode): boolean {
314
+ rehydrateNode(node: AstNode): void {
291
315
  if (node.$cstNode !== undefined) {
292
- return true;
316
+ return;
293
317
  }
294
- return this.rehydrate(AstUtils.getDocument(node));
318
+ this.rehydrate(AstUtils.getDocument(node));
295
319
  }
296
320
 
297
321
  /**
@@ -353,8 +377,8 @@ export class CstResidencyService {
353
377
  this.shedTotal += this.shed(document);
354
378
  }
355
379
 
356
- /** Cancel and drop every idle timer for clean shutdown and deterministic tests. */
357
- dispose(): void {
380
+ /** Cancel every armed shed, so a document that has gone idle keeps its CST. */
381
+ cancelPendingShed(): void {
358
382
  for (const timer of this.idleTimers.values()) {
359
383
  timer.dispose();
360
384
  }
@@ -24,7 +24,6 @@ import {
24
24
  type AstNodeLocator,
25
25
  AstUtils,
26
26
  DefaultScopeProvider,
27
- type LangiumDocuments,
28
27
  MapScope,
29
28
  type ReferenceInfo,
30
29
  type Scope,
@@ -35,9 +34,11 @@ import {
35
34
  WorkspaceCache,
36
35
  stream
37
36
  } from '@hydranium/langium';
37
+ import { buildAstNode } from '../ast-extension/ast-node-builder.js';
38
38
  import { type LogNameOptions } from '../diagnostics/logger.js';
39
39
  import { type HydraniumLanguageServices } from '../language-module.js';
40
40
  import { type NameProvider } from '../naming/name-provider.js';
41
+ import { type HydraniumDocumentRegistry } from '../workspace/langium-documents.js';
41
42
  import { type ScopeExtensionService } from './scope-extension-service.js';
42
43
  import { isTieredDescription } from './scoped-ast-node-description.js';
43
44
 
@@ -143,7 +144,7 @@ export interface ScopeContext {
143
144
  * `reference-candidate-provider.ts` module.
144
145
  */
145
146
  export class HydraniumScopeProvider extends DefaultScopeProvider {
146
- protected readonly langiumDocuments: LangiumDocuments;
147
+ protected readonly langiumDocuments: HydraniumDocumentRegistry;
147
148
  protected readonly astNodeLocator: AstNodeLocator;
148
149
  protected readonly scopeExtensionService: ScopeExtensionService;
149
150
  protected readonly options: HydraniumScopeProviderOptions;
@@ -469,12 +470,13 @@ export class HydraniumScopeProvider extends DefaultScopeProvider {
469
470
  * Convert a protocol-layer {@link ReferenceContext} into a Langium
470
471
  * {@link ReferenceInfo} the rest of the scope/linking machinery accepts.
471
472
  *
472
- * Walks `syntheticPath` by FABRICATING a type-only stub per step, so a
473
- * scope can be queried for an element that does not exist yet — which is
474
- * what synthetic paths are for. The stubs carry no children, so a caller
475
- * that needs to read a collection off the leaf wants
476
- * {@link resolveReferenceSource} instead, which walks the same path into
477
- * the real tree.
473
+ * Walks `syntheticPath` by FABRICATING a stub per step, so a scope can be
474
+ * queried for an element that does not exist yet — which is what synthetic
475
+ * paths are for. A stub carries the grammar's declared defaults and nothing
476
+ * else, so its containment lists are present but EMPTY: a caller that needs
477
+ * to read a populated collection off the leaf wants
478
+ * {@link resolveReferenceSource} instead, which walks the same path into the
479
+ * real tree.
478
480
  *
479
481
  * Throws if the context references an unresolvable source; callers
480
482
  * that prefer a soft failure should catch and fall back to
@@ -486,16 +488,15 @@ export class HydraniumScopeProvider extends DefaultScopeProvider {
486
488
  throw new Error('Invalid reference source');
487
489
  }
488
490
  for (const step of ctx.syntheticPath ?? []) {
489
- container = {
491
+ container = buildAstNode(this.services.shared.AstReflection, step.type, {
490
492
  $container: container,
491
493
  $containerProperty: step.containerProperty,
492
494
  // Part of Langium's own container contract, so a stub that omits it
493
495
  // is an under-specified node: anything reading position off the
494
496
  // chain (a key provider, an adopter scope extension) sees
495
497
  // `undefined` where the caller named a slot.
496
- $containerIndex: step.index,
497
- $type: step.type
498
- };
498
+ $containerIndex: step.index
499
+ });
499
500
  }
500
501
  return {
501
502
  reference: { $refText: '', ref: undefined },
@@ -586,18 +587,35 @@ export class HydraniumScopeProvider extends DefaultScopeProvider {
586
587
  }
587
588
 
588
589
  /**
589
- * Build a transient AST-node stub for a {@link SyntheticSource} request.
590
- * Default: looks up the document via `LangiumDocuments` and uses its parse
591
- * root as the container; returns `undefined` if the document isn't loaded.
592
- * Consumers that need to materialise an empty document on demand (e.g.
593
- * to query the scope before a file exists) override this.
590
+ * Build a transient AST-node stub for a {@link SyntheticSource} request: a
591
+ * node of the requested type, contained by the document at `source.uri`.
592
+ *
593
+ * **The container is materialised when no document is loaded there**, which
594
+ * is the case the source type exists for — a `SyntheticSource` names a node
595
+ * that does not exist yet, and the create-element flow asks at the FOLDER
596
+ * the file is about to be written into. Abstaining there would answer an
597
+ * empty candidate list, which a client cannot tell from "nothing matches".
598
+ *
599
+ * The stand-in parses under THIS provider's grammar, because a folder URI
600
+ * carries no extension for the routing ladder to end on and this provider is
601
+ * bound per grammar. Reaching for `createEmptyDocument(uri)` without the id
602
+ * instead fails inside the parse, on an empty extension rather than on the
603
+ * URI.
604
+ *
605
+ * The materialised document is unregistered and transient; see
606
+ * `createEmptyDocument`. Overriding is still open to a consumer whose
607
+ * "container" is an inner element rather than the parse root, or one that
608
+ * deliberately declines to answer for an absent document.
609
+ *
610
+ * The stub carries the grammar's declared defaults, so an extension reading a
611
+ * containment list off it sees an empty array rather than `undefined`.
594
612
  */
595
613
  protected resolveSyntheticSource(source: SyntheticSource): AstNode | undefined {
596
- const document = this.langiumDocuments.getDocument(UriUtils.toUri(source.uri));
597
- if (!document) {
598
- return undefined;
599
- }
600
- return { $type: source.type, $container: document.parseResult.value };
614
+ const uri = UriUtils.toUri(source.uri);
615
+ const document =
616
+ this.langiumDocuments.getDocument(uri) ??
617
+ this.langiumDocuments.createEmptyDocument(uri, this.services.LanguageMetaData.languageId);
618
+ return buildAstNode(this.services.shared.AstReflection, source.type, { $container: document.parseResult.value });
601
619
  }
602
620
 
603
621
  /**
@@ -9,8 +9,11 @@
9
9
 
10
10
  import type { Clock, Logger, Project, Tracer } from '@hydranium/protocol';
11
11
  import type { LangiumSharedCoreServices } from '@hydranium/langium';
12
+ import type { ServerLocale } from '../locale/server-locale.js';
13
+ import type { MessageRenderer } from '../messages/renderer.js';
12
14
  import type { SelfSaveRegistry } from '../documents/self-save-registry.js';
13
15
  import type { WritableFileSystemProvider } from '../documents/ast-document-manager.js';
16
+ import type { HydraniumDocumentRegistry } from './workspace/langium-documents.js';
14
17
  import type { BuildPhasePassService } from './build-phase-pass/build-phase-pass-service.js';
15
18
  import type { CstResidencyService } from './residency/cst-residency-service.js';
16
19
  import type { BuildPipelineIntegration } from './document-builder/build-pipeline-integration.js';
@@ -27,8 +30,9 @@ import type { AdditionalDocumentContribution } from './workspace/additional-docu
27
30
  * framework additions that other framework services consume: the dedicated
28
31
  * {@link Clock}, {@link Logger} and {@link Tracer} top-level slots (injectable
29
32
  * time source, emission-only logger, and the measure-and-emit tracer composed
30
- * from the other two), the {@link AdditionalDocumentContribution} group, an
31
- * {@link ExtendedServiceRegistry}, and on `workspace` a writable file-system
33
+ * from the other two), the {@link AdditionalDocumentContribution} group, the
34
+ * {@link MessageRenderer} and the {@link ServerLocale} it renders in,
35
+ * an {@link ExtendedServiceRegistry}, and on `workspace` a writable file-system
32
36
  * provider plus {@link HydraniumWorkspaceManager}, {@link ProjectManager},
33
37
  * {@link SelfSaveRegistry}, {@link BuildPipelineIntegration},
34
38
  * {@link BuildPhasePassService}, {@link CstResidencyService} and
@@ -57,6 +61,14 @@ export interface ServerSharedServicesMinimal<TProject extends Project = Project>
57
61
  * adopters deep-merge contributions that seed built-in / stdlib documents.
58
62
  */
59
63
  additionalDocuments: Record<string, AdditionalDocumentContribution>;
64
+ /**
65
+ * Renders each user-facing message once, before the server sends it. On the
66
+ * shared tier with no workspace dependency, because all three heads'
67
+ * messages pass through it.
68
+ */
69
+ MessageRenderer: MessageRenderer;
70
+ /** The locale an init handed the server, for whoever renders in it. */
71
+ ServerLocale: ServerLocale;
60
72
  /**
61
73
  * Narrows Langium's base `ServiceRegistry` slot to the framework impl the
62
74
  * framework always binds, so the abstaining lookups — `getServicesFor`
@@ -75,6 +87,11 @@ export interface ServerSharedServicesMinimal<TProject extends Project = Project>
75
87
  // framework always binds, so `wsRelativePath` and the folder-walk are
76
88
  // reachable from the minimal surface without a cast.
77
89
  WorkspaceManager: HydraniumWorkspaceManager;
90
+ // Same, for the registry: the framework always binds
91
+ // `HydraniumLangiumDocuments`, and `createEmptyDocument` is reachable
92
+ // only through this narrowing — a scope provider querying a URI before
93
+ // the file exists is the caller that needs it.
94
+ /* override */ LangiumDocuments: HydraniumDocumentRegistry;
78
95
  ProjectManager: ProjectManager<TProject>;
79
96
  SelfSaveRegistry: SelfSaveRegistry;
80
97
  BuildPipelineIntegration: BuildPipelineIntegration;
@@ -8,6 +8,7 @@
8
8
  ********************************************************************************/
9
9
 
10
10
  import {
11
+ hasMessageIdentity,
11
12
  type Tracer,
12
13
  type TransferDiagnostic,
13
14
  type TransferElement,
@@ -79,6 +80,37 @@ export interface TransferEnvelopeSource<TDiagnostic> {
79
80
  readonly diagnostics: readonly (TDiagnostic | Diagnostic)[];
80
81
  }
81
82
 
83
+ /**
84
+ * The AST→transfer contract a DI slot holds, implemented by
85
+ * {@link DefaultTransferEncoder}.
86
+ *
87
+ * **This is an interface and not the class, and that is load-bearing.** A class
88
+ * in a slot drags its `protected` members into every assignability check, which
89
+ * TypeScript compares NOMINALLY — so the slot type could not be satisfied by a
90
+ * subclass declared against a second physical copy of this package, and an
91
+ * adopter narrowing the slot had to intersect with the framework's declaration
92
+ * rather than replace it, leaving method resolution dependent on declaration
93
+ * order. An interface has no protected members and is compared structurally, so
94
+ * neither applies.
95
+ *
96
+ * **The transfer returns are the structural base ({@link TransferElement}), not
97
+ * the per-grammar overlay.** The overlay cannot parameterise this contract:
98
+ * `TransferTypeFor` reaches `keyof TTransferMap`, which makes that parameter
99
+ * measured-INVARIANT, and invariant parameters relate only when their arguments
100
+ * are mutually assignable — so a map-parameterised contract admits no adopter
101
+ * instantiation at all. Heads read this contract and do not know adopter maps;
102
+ * an adopter recovers the precise type by declaring its own slot, which it can
103
+ * now do by replacement.
104
+ */
105
+ export interface TransferEncoder<TDiagnostic extends TransferDiagnostic = TransferDiagnostic> {
106
+ toTransfer<T extends AstNode>(ast: T, mode?: TransferMode): TransferElement;
107
+ toTransferDocument(langiumDocument: LangiumDocument): TransferDocument<TransferElement, TDiagnostic>;
108
+ astDocumentToTransferDocument<TAst extends AstNode>(
109
+ document: AstDocument<TAst, TDiagnostic | TransferLspDiagnostic>
110
+ ): TransferDocument<TransferElement, TDiagnostic>;
111
+ toTransferDiagnostic(diagnostic: TransferLspDiagnostic): TDiagnostic;
112
+ }
113
+
82
114
  /**
83
115
  * One-directional structural mapper from a Langium AST into the wire
84
116
  * transfer-model shape ({@link TransferElement}-based JSON).
@@ -123,7 +155,7 @@ export interface TransferEnvelopeSource<TDiagnostic> {
123
155
  * - {@link toTransferDiagnostic} — project a {@link TransferLspDiagnostic}
124
156
  * (the framework validator's output) to {@link TDiagnostic}.
125
157
  */
126
- export class TransferEncoder<
158
+ export class DefaultTransferEncoder<
127
159
  // The map is intentionally unconstrained — adopters supply typed
128
160
  // overlays whose specific-key shapes don't structurally satisfy a
129
161
  // `Record<string, TransferElement>` index signature. `TransferTypeFor`
@@ -387,7 +419,10 @@ export class TransferEncoder<
387
419
  * LSP severity enum to the wire string union, discriminates the
388
420
  * diagnostic type from Langium's `data.code` (`'lexing-error'` /
389
421
  * `'parsing-error'` else `'validation-error'`), passes through
390
- * message / element / property / code. Adopters whose validator
422
+ * message / element / property / code, and lifts the framework message
423
+ * params out of `data` so a translating surface can render a
424
+ * parameterised diagnostic rather than a template with its placeholders
425
+ * left standing. Adopters whose validator
391
426
  * doesn't decorate diagnostics with `element` still get a valid
392
427
  * `TransferDiagnostic` — the field falls back to `''`.
393
428
  *
@@ -396,6 +431,12 @@ export class TransferEncoder<
396
431
  */
397
432
  toTransferDiagnostic(diagnostic: TransferLspDiagnostic): TDiagnostic {
398
433
  const langiumCode = (diagnostic.data as { code?: string } | undefined)?.code;
434
+ // The same `data` the Langium code comes out of also carries the framework
435
+ // message identity, under its own key so the two conventions co-exist.
436
+ // Taking the params from there rather than from `code` is what lets a
437
+ // translating surface render a PARAMETERISED diagnostic: `code` survives on
438
+ // its own and yields a template with its placeholders left standing.
439
+ const identity = hasMessageIdentity(diagnostic.data) ? diagnostic.data.hydranium : undefined;
399
440
  const result: TransferDiagnostic = {
400
441
  type: langiumCode === 'lexing-error' ? 'lexing-error' : langiumCode === 'parsing-error' ? 'parsing-error' : 'validation-error',
401
442
  element: diagnostic.element ?? '',
@@ -408,7 +449,8 @@ export class TransferEncoder<
408
449
  : diagnostic.severity === DiagnosticSeverity.Warning
409
450
  ? 'warning'
410
451
  : 'info',
411
- code: typeof diagnostic.code === 'number' || typeof diagnostic.code === 'string' ? diagnostic.code : langiumCode
452
+ code: typeof diagnostic.code === 'number' || typeof diagnostic.code === 'string' ? diagnostic.code : langiumCode,
453
+ params: identity?.params
412
454
  };
413
455
  return result as TDiagnostic;
414
456
  }
@@ -7,12 +7,23 @@
7
7
  * SPDX-License-Identifier: MIT
8
8
  ********************************************************************************/
9
9
 
10
- import { type LogThreshold, type MaybeObservableValue, ObservableValue, type Tracer, TransferDiagnostic } from '@hydranium/protocol';
10
+ import {
11
+ defineMessage,
12
+ describeError,
13
+ messageData,
14
+ type LogThreshold,
15
+ type MaybeObservableValue,
16
+ ObservableValue,
17
+ type Tracer,
18
+ TransferDiagnostic
19
+ } from '@hydranium/protocol';
11
20
  import {
12
21
  type AstNode,
13
22
  type AstNodeLocator,
23
+ type AstReflection,
14
24
  DefaultDocumentValidator,
15
25
  type DiagnosticInfo,
26
+ DocumentValidator,
16
27
  type LangiumDocument,
17
28
  type LangiumCoreServices,
18
29
  type ValidateSingleNodeOptions,
@@ -20,21 +31,102 @@ import {
20
31
  type ValidationSeverity
21
32
  } from '@hydranium/langium';
22
33
  import type { CancellationToken } from 'vscode-languageserver-protocol';
23
- import type { Diagnostic } from 'vscode-languageserver-types';
34
+ // A VALUE import, for `Diagnostic.getMessageString`: `message` is
35
+ // `string | MarkupContent` in LSP 3.17+, so upstream's own reader is what
36
+ // narrows it rather than a hand-rolled union check here.
37
+ import { Diagnostic } from 'vscode-languageserver-types';
24
38
  import { type LogNameOptions } from '../diagnostics/logger.js';
25
39
  import { isSyntheticNode } from '../workspace/synthetic.js';
26
40
  import { isVirtualUri } from '../workspace/virtual-document.js';
27
41
 
28
42
  /**
29
- * Diagnostic shape produced by {@link HydraniumDocumentValidator}: an LSP
30
- * {@link Diagnostic} extended with the protocol-level `element` path and
31
- * optional `property` name from {@link TransferDiagnostic}.
43
+ * Diagnostic read off a `LangiumDocument`: an LSP {@link Diagnostic} that MAY
44
+ * carry the protocol-level `element` path and `property` name from
45
+ * {@link TransferDiagnostic}.
46
+ *
47
+ * `element` is optional because a document's diagnostics do not all come from
48
+ * this validator. {@link HydraniumDocumentValidator.toDiagnostic} always sets
49
+ * one, but Langium pushes lexer and parser errors straight onto the document
50
+ * without routing them through it, so a document that fails to parse carries
51
+ * diagnostics with no path at all. Treat it as absent, not empty.
52
+ *
53
+ * Narrowing `LangiumDocument.diagnostics` to this type instead is unavailable:
54
+ * declaration merging may add a member but not retype one, and augmenting the
55
+ * LSP `Diagnostic` reaches only one of the two declaration files its package
56
+ * ships, since the `exports` map splits `import` from `default` with no `types`
57
+ * condition. Consumers therefore cast at the read, and the cast is sound only
58
+ * because this field is optional.
32
59
  */
33
60
  export interface TransferLspDiagnostic extends Diagnostic {
34
- element: string;
61
+ element?: string;
35
62
  property?: string;
36
63
  }
37
64
 
65
+ /**
66
+ * A reference resolved to nothing.
67
+ *
68
+ * **The English is byte-identical to Langium's `DefaultLinker.createLinkingError`
69
+ * sentence, and must stay so.** The identity is attached to a diagnostic Langium
70
+ * already worded, so a divergence here would silently change the text every
71
+ * adopter without a catalogue sees. {@link HydraniumDocumentValidator.processLinkingErrors}
72
+ * attaches it only when the two match exactly, which is also what keeps an
73
+ * adopter's own reworded linking error from being mislabelled as this one.
74
+ *
75
+ * It exists because this is the most-seen validation error in any language built
76
+ * on the framework, and Langium puts its own code in `data.code` rather than on
77
+ * `Diagnostic.code` — so without a framework identity every adopter wanting to
78
+ * render it has to special-case Langium's shape.
79
+ */
80
+ export const UNRESOLVED_REFERENCE = defineMessage(
81
+ 'hydranium/core/unresolved-reference',
82
+ "Could not resolve reference to {referenceType} named '{refText}'."
83
+ );
84
+
85
+ /**
86
+ * A character no token of the grammar can start with.
87
+ *
88
+ * **The English is byte-identical to CHEVROTAIN's
89
+ * `defaultLexerErrorProvider.buildUnexpectedCharactersMessage`, and must stay
90
+ * so** — one layer further out than {@link UNRESOLVED_REFERENCE}, whose sentence
91
+ * is Langium's. Langium words neither: `processLexingErrors` copies
92
+ * `lexerDiagnostic.message` through untouched, so the text an adopter sees today
93
+ * is produced two dependencies down and is the only thing this identity may
94
+ * claim to be. {@link HydraniumDocumentValidator.identifyLexingError} attaches
95
+ * it only when the two match exactly, which is also what keeps a custom lexer's
96
+ * own diagnostics — Langium admits any of them through `lexerReport` — from
97
+ * being mislabelled as this one.
98
+ *
99
+ * It exists because a lexing error is the FIRST message a user of a new language
100
+ * sees and the one an adopter cannot reach: every other diagnostic worth
101
+ * translating either carries an identity already or is raised by adopter code,
102
+ * while this one arrives with a Langium `data.code` naming a KIND and no
103
+ * parameters at all — so a catalogue had nothing to key on and nothing to
104
+ * interpolate.
105
+ *
106
+ * `skipped` rather than `length`, matching what the sentence says the number
107
+ * means: chevrotain reports how many characters the lexer discarded to recover,
108
+ * which for a single stray character is one and for a run of them is the run.
109
+ */
110
+ export const LEXING_ERROR = defineMessage(
111
+ 'hydranium/core/lexing-error',
112
+ 'unexpected character: ->{character}<- at offset: {offset}, skipped {skipped} characters.'
113
+ );
114
+
115
+ /**
116
+ * Langium's own `data.code` values for a diagnostic that came out of the lexer.
117
+ *
118
+ * All four severities, not just the error one: `lexerReport` admits warnings and
119
+ * below, and a token builder that downgrades a stray character still produces
120
+ * the same sentence. Gating on the error code alone would leave the identity off
121
+ * a message that is word-for-word the one it names.
122
+ */
123
+ const LEXING_CODES: ReadonlySet<unknown> = new Set([
124
+ DocumentValidator.LexingError,
125
+ DocumentValidator.LexingWarning,
126
+ DocumentValidator.LexingInfo,
127
+ DocumentValidator.LexingHint
128
+ ]);
129
+
38
130
  export interface DocumentValidatorOptions extends LogNameOptions {
39
131
  /**
40
132
  * Level at which the `validateDocument` timing line is emitted, or `'off'`
@@ -81,6 +173,7 @@ export interface DocumentValidatorOptions extends LogNameOptions {
81
173
  export class HydraniumDocumentValidator extends DefaultDocumentValidator {
82
174
  protected readonly tracer: Tracer;
83
175
  protected readonly astNodeLocator: AstNodeLocator;
176
+ protected readonly reflection: AstReflection;
84
177
  protected readonly logLevel: ObservableValue<LogThreshold>;
85
178
  protected readonly logAfterMs: ObservableValue<number>;
86
179
  protected readonly validateVirtualDocuments: ObservableValue<boolean>;
@@ -90,6 +183,7 @@ export class HydraniumDocumentValidator extends DefaultDocumentValidator {
90
183
  super(services);
91
184
  this.tracer = services.shared.Tracer.for(options.logName ?? 'DocumentValidator').trace('instantiated');
92
185
  this.astNodeLocator = services.workspace.AstNodeLocator;
186
+ this.reflection = services.shared.AstReflection;
93
187
  this.logLevel = ObservableValue.from(options.logLevel ?? 'debug');
94
188
  this.logAfterMs = ObservableValue.from(options.logAfterMs ?? 20);
95
189
  this.validateVirtualDocuments = ObservableValue.from(options.validateVirtualDocuments ?? false);
@@ -111,16 +205,85 @@ export class HydraniumDocumentValidator extends DefaultDocumentValidator {
111
205
  }
112
206
  const level = this.logLevel.value;
113
207
  if (level === 'off') {
114
- return super.validateDocument(document, options, cancelToken);
208
+ return this.validateAndIdentify(document, options, cancelToken);
115
209
  }
116
210
  // `level` is narrowed to `LogLevel` past the early-return.
117
211
  return this.tracer
118
212
  .withUri(document.uri.toString())
119
- .time('validateDocument', () => super.validateDocument(document, options, cancelToken), level, {
213
+ .time('validateDocument', () => this.validateAndIdentify(document, options, cancelToken), level, {
120
214
  logAfterMs: this.logAfterMs.value
121
215
  });
122
216
  }
123
217
 
218
+ /**
219
+ * Langium's validation pass, plus the framework identity on the lexing
220
+ * diagnostics it produced.
221
+ *
222
+ * **Here rather than in an override of `processLexingErrors`, and the reason
223
+ * is that the seam cannot see what the identity needs.** Langium hands that
224
+ * method a `ParseResult`, which carries the AST and the error lists but not
225
+ * the source text — and the offending CHARACTER is the parameter a
226
+ * translation exists to interpolate. The document does carry it, and this is
227
+ * the innermost point that still holds one. Reconstructing the character by
228
+ * matching it out of the finished sentence was the alternative, and it
229
+ * inverts the direction the rest of this file works in: every other identity
230
+ * here is derived from structured fields and CHECKED against the prose.
231
+ *
232
+ * Inside the timing span rather than around it, so the line accounts for the
233
+ * whole pass.
234
+ */
235
+ protected async validateAndIdentify(
236
+ document: LangiumDocument,
237
+ options?: ValidationOptions,
238
+ cancelToken?: CancellationToken
239
+ ): Promise<Diagnostic[]> {
240
+ const diagnostics = await super.validateDocument(document, options, cancelToken);
241
+ // Mapped in place over the array Langium built, rather than filtered and
242
+ // re-concatenated: the publish order is the diagnostic order and a
243
+ // reordering would move a squiggle's entry in the problems list.
244
+ for (let index = 0; index < diagnostics.length; index++) {
245
+ diagnostics[index] = this.identifyLexingError(document, diagnostics[index]);
246
+ }
247
+ return diagnostics;
248
+ }
249
+
250
+ /**
251
+ * Add the {@link LEXING_ERROR} identity to one diagnostic, or return it
252
+ * untouched when it is not the sentence that identity renders.
253
+ *
254
+ * The parameters come from the diagnostic's own RANGE, not from
255
+ * `parseResult.lexerErrors`. Both hold the same numbers, and the range is the
256
+ * one that needs no assumption about upstream: correlating the two lists
257
+ * would depend on Langium appending one diagnostic per lexer error in order,
258
+ * which is true today and is an internal of the method being wrapped.
259
+ *
260
+ * **The format-and-compare is the whole discriminator, and it validates the
261
+ * reconstruction as well as the identity.** A range that did not round-trip
262
+ * to the offset chevrotain reported would produce a different sentence and be
263
+ * declined, so a wrong parameter set can never be attached to a right-looking
264
+ * message.
265
+ */
266
+ protected identifyLexingError(document: LangiumDocument, diagnostic: Diagnostic): Diagnostic {
267
+ const data = diagnostic.data as { code?: unknown } | undefined;
268
+ if (!LEXING_CODES.has(data?.code)) {
269
+ return diagnostic;
270
+ }
271
+ const text = document.textDocument;
272
+ const offset = text.offsetAt(diagnostic.range.start);
273
+ const params = {
274
+ character: text.getText().charAt(offset),
275
+ offset,
276
+ skipped: text.offsetAt(diagnostic.range.end) - offset
277
+ };
278
+ if (Diagnostic.getMessageString(diagnostic) !== LEXING_ERROR.format(params)) {
279
+ return diagnostic;
280
+ }
281
+ // Merged OVER Langium's data, so `data.code` survives for the readers that
282
+ // switch on it — `stopAfterLexingErrors` is one, and the GLSP head's
283
+ // read-only decision is another.
284
+ return { ...diagnostic, code: LEXING_ERROR.code, data: { ...data, ...messageData(LEXING_ERROR, params) } };
285
+ }
286
+
124
287
  /**
125
288
  * Skip validation for a node **and its children** when
126
289
  * {@link shouldSkipValidation} returns true.
@@ -144,6 +307,90 @@ export class HydraniumDocumentValidator extends DefaultDocumentValidator {
144
307
  return !this.validateSyntheticNodes.value && isSyntheticNode(node);
145
308
  }
146
309
 
310
+ /**
311
+ * Langium's linking-error pass, plus the framework identity on each
312
+ * diagnostic it produced.
313
+ *
314
+ * Langium puts its own `linking-error` marker in `data.code` and leaves
315
+ * `Diagnostic.code` unset, so nothing identifies the message on a surface
316
+ * that drops `data` — which is every editor surface. This adds the framework
317
+ * identity to both `code` and `data.hydranium` while LEAVING `data.code` in
318
+ * place: `stopAfterLinkingErrors` and Langium's code-action dispatch both
319
+ * read it.
320
+ *
321
+ * **The identity is attached only when the message is the one
322
+ * {@link UNRESOLVED_REFERENCE} renders.** Two other sentences reach this
323
+ * list: the linker's exception form, raised when resolution itself throws,
324
+ * and whatever an adopter overriding `createLinkingError` chose. Labelling
325
+ * either would make a catalogue render the wrong sentence — and for the
326
+ * exception form it would discard the underlying cause. Comparing against
327
+ * the locally rendered English is what discriminates; there is no structural
328
+ * field that does.
329
+ */
330
+ protected override processLinkingErrors(document: LangiumDocument, diagnostics: Diagnostic[], options: ValidationOptions): void {
331
+ const from = diagnostics.length;
332
+ super.processLinkingErrors(document, diagnostics, options);
333
+ for (let index = from; index < diagnostics.length; index++) {
334
+ diagnostics[index] = this.identifyLinkingError(diagnostics[index]);
335
+ }
336
+ }
337
+
338
+ /**
339
+ * Add the {@link UNRESOLVED_REFERENCE} identity to one linking diagnostic,
340
+ * or return it untouched when its message is not the sentence that identity
341
+ * renders.
342
+ *
343
+ * `refText` comes from the `data` Langium populated; `referenceType` is not
344
+ * in it, so it is recovered the same way `createLinkingError` produced it —
345
+ * through the reflection, from the container type and property.
346
+ */
347
+ protected identifyLinkingError(diagnostic: Diagnostic): Diagnostic {
348
+ const data = diagnostic.data as { code?: unknown; refText?: unknown; containerType?: unknown; property?: unknown } | undefined;
349
+ if (typeof data?.refText !== 'string' || typeof data.containerType !== 'string' || typeof data.property !== 'string') {
350
+ return diagnostic;
351
+ }
352
+ const referenceType = this.referenceTypeOf(data.containerType, data.property, data.refText);
353
+ if (referenceType === undefined) {
354
+ return diagnostic;
355
+ }
356
+ const params = { referenceType, refText: data.refText };
357
+ if (diagnostic.message !== UNRESOLVED_REFERENCE.format(params)) {
358
+ return diagnostic;
359
+ }
360
+ // Merged OVER Langium's data rather than replacing it, so `data.code`
361
+ // survives for the readers that switch on it.
362
+ return { ...diagnostic, code: UNRESOLVED_REFERENCE.code, data: { ...data, ...messageData(UNRESOLVED_REFERENCE, params) } };
363
+ }
364
+
365
+ /**
366
+ * The declared target type of the reference this diagnostic came from, or
367
+ * `undefined` when the reflection cannot name one.
368
+ *
369
+ * **The lookup can throw, and that is the reason this is a method rather
370
+ * than an inline call.** `AbstractAstReflection.getReferenceType` raises on
371
+ * an unknown container `$type` and on a property that is not a reference —
372
+ * and the linking error whose type it cannot name is the one most likely to
373
+ * reach here, because `DefaultLinker` catches its OWN failed lookup and
374
+ * turns it into the exception-form message. Rethrowing would take
375
+ * `validateDocument` with it, since Langium wraps `processLinkingErrors` in
376
+ * no try: a diagnostic Langium degraded gracefully would become a failed
377
+ * build. Declining is also the right answer on the merits — a reference
378
+ * whose type cannot be named is not the message
379
+ * {@link UNRESOLVED_REFERENCE} claims.
380
+ */
381
+ protected referenceTypeOf(containerType: string, property: string, refText: string): string | undefined {
382
+ try {
383
+ return this.reflection.getReferenceType({
384
+ container: { $type: containerType } as AstNode,
385
+ property,
386
+ reference: { $refText: refText }
387
+ } as Parameters<AstReflection['getReferenceType']>[0]);
388
+ } catch (err: unknown) {
389
+ this.tracer.debug(`cannot name the reference type for ${containerType}.${property}: ${describeError(err)}`);
390
+ return undefined;
391
+ }
392
+ }
393
+
147
394
  protected override toDiagnostic<N extends AstNode>(
148
395
  severity: ValidationSeverity,
149
396
  message: string,