langium-tools 0.4.0 → 0.5.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.
@@ -44,6 +44,72 @@ export var DocumentIssueSeverity;
44
44
  function diagnosticMessage(message) {
45
45
  return typeof message === 'string' ? message : message.value;
46
46
  }
47
+ /** Codes Langium's `DocumentValidator` stores on copied lexer and parser diagnostics. */
48
+ const LEXING_ERROR = "lexing-error";
49
+ const PARSING_ERROR = "parsing-error";
50
+ function diagnosticCode(diagnostic) {
51
+ const data = diagnostic.data;
52
+ if (typeof data !== "object" || data === null || !("code" in data)) {
53
+ return undefined;
54
+ }
55
+ const code = data.code;
56
+ return typeof code === "string" ? code : undefined;
57
+ }
58
+ function syntaxSource(diagnostic) {
59
+ const code = diagnosticCode(diagnostic);
60
+ if (code === LEXING_ERROR) {
61
+ return DocumentIssueSource.LEXER;
62
+ }
63
+ if (code === PARSING_ERROR) {
64
+ return DocumentIssueSource.PARSER;
65
+ }
66
+ return undefined;
67
+ }
68
+ /**
69
+ * Langium copies each lexer and parser error into `document.diagnostics` after validation.
70
+ * Prefer that copy: its range has an end position. Keep the offset from `parseResult`.
71
+ * A `parseResult` error with no matching diagnostic is kept as it is.
72
+ */
73
+ function mergeSyntaxErrors(errors, diagnostics, source, fromParseResult, messageOf) {
74
+ const issues = [];
75
+ const used = new Set();
76
+ for (const error of errors) {
77
+ const message = messageOf(error);
78
+ const match = diagnostics.findIndex((diagnostic, index) => !used.has(index) && diagnosticMessage(diagnostic.message) === message);
79
+ const parsed = fromParseResult(error);
80
+ if (match >= 0) {
81
+ used.add(match);
82
+ const diagnostic = diagnostics[match];
83
+ issues.push({
84
+ source,
85
+ severity: mapSeverity(diagnostic.severity),
86
+ message: diagnosticMessage(diagnostic.message),
87
+ startOffset: parsed.startOffset,
88
+ startLine: diagnostic.range.start.line,
89
+ startColumn: diagnostic.range.start.character,
90
+ endLine: diagnostic.range.end.line,
91
+ endColumn: diagnostic.range.end.character,
92
+ });
93
+ }
94
+ else {
95
+ issues.push(parsed);
96
+ }
97
+ }
98
+ diagnostics.forEach((diagnostic, index) => {
99
+ if (!used.has(index)) {
100
+ issues.push({
101
+ source,
102
+ severity: mapSeverity(diagnostic.severity),
103
+ message: diagnosticMessage(diagnostic.message),
104
+ startLine: diagnostic.range.start.line,
105
+ startColumn: diagnostic.range.start.character,
106
+ endLine: diagnostic.range.end.line,
107
+ endColumn: diagnostic.range.end.character,
108
+ });
109
+ }
110
+ });
111
+ return issues;
112
+ }
47
113
  function mapSeverity(severity) {
48
114
  if (!severity) {
49
115
  return DocumentIssueSeverity.UNKNOWN;
@@ -76,40 +142,38 @@ function mapSeverity(severity) {
76
142
  export function getDocumentIssues(document, params) {
77
143
  var _a;
78
144
  const { skipNonErrorDiagnostics = false, skipLexerErrors = false, skipParserErrors = false, skipValidation = false, } = params || {};
145
+ const diagnostics = (_a = document.diagnostics) !== null && _a !== void 0 ? _a : [];
79
146
  const issues = [];
80
147
  if (!skipLexerErrors) {
81
- document.parseResult.lexerErrors.forEach((lexerIssue) => {
82
- issues.push({
83
- source: DocumentIssueSource.LEXER,
84
- message: lexerIssue.message,
85
- severity: DocumentIssueSeverity.ERROR,
86
- startOffset: lexerIssue.offset,
87
- startLine: plus(lexerIssue.line, -1),
88
- startColumn: plus(lexerIssue.column, -1),
89
- });
90
- });
148
+ issues.push(...mergeSyntaxErrors(document.parseResult.lexerErrors, diagnostics.filter((diagnostic) => syntaxSource(diagnostic) === DocumentIssueSource.LEXER), DocumentIssueSource.LEXER, (lexerIssue) => ({
149
+ source: DocumentIssueSource.LEXER,
150
+ message: lexerIssue.message,
151
+ severity: DocumentIssueSeverity.ERROR,
152
+ startOffset: lexerIssue.offset,
153
+ startLine: plus(lexerIssue.line, -1),
154
+ startColumn: plus(lexerIssue.column, -1),
155
+ }), (lexerIssue) => lexerIssue.message));
91
156
  }
92
157
  if (!skipParserErrors) {
93
- document.parseResult.parserErrors.forEach((parserError) => {
158
+ issues.push(...mergeSyntaxErrors(document.parseResult.parserErrors, diagnostics.filter((diagnostic) => syntaxSource(diagnostic) === DocumentIssueSource.PARSER), DocumentIssueSource.PARSER, (parserError) => {
94
159
  // Chevrotain exposes the token before the failure. Inserted EOF tokens use -1
95
160
  // for offset, line, and column, which is not a real position.
96
161
  const previousToken = parserError === null || parserError === void 0 ? void 0 : parserError.previousToken;
97
- issues.push({
162
+ return {
98
163
  source: DocumentIssueSource.PARSER,
99
164
  severity: DocumentIssueSeverity.ERROR,
100
165
  message: parserError.message,
101
166
  startOffset: firstDefinedNumber(parserError.token.startOffset, previousToken === null || previousToken === void 0 ? void 0 : previousToken.startOffset),
102
167
  startLine: plus(firstDefinedNumber(parserError.token.startLine, previousToken === null || previousToken === void 0 ? void 0 : previousToken.startLine), -1),
103
168
  startColumn: plus(firstDefinedNumber(parserError.token.startColumn, previousToken === null || previousToken === void 0 ? void 0 : previousToken.startColumn), -1),
104
- // Unrelieable end position returned by Chevrotain (24.09.2024)
105
- // endOffset: firstDefinedNumber(parserError.token.endOffset, previousToken?.endOffset),
106
- // endLine: plus(firstDefinedNumber(parserError.token.endLine, previousToken?.endLine), -1),
107
- // endColumn: plus(firstDefinedNumber(parserError.token.endColumn, previousToken?.endColumn), 1),
108
- });
109
- });
169
+ };
170
+ }, (parserError) => parserError.message));
110
171
  }
111
172
  if (!skipValidation) {
112
- (_a = document.diagnostics) === null || _a === void 0 ? void 0 : _a.forEach((diagnostic) => {
173
+ diagnostics.forEach((diagnostic) => {
174
+ if (syntaxSource(diagnostic)) {
175
+ return;
176
+ }
113
177
  if (!skipNonErrorDiagnostics || diagnostic.severity === DiagnosticSeverity.Error) {
114
178
  issues.push({
115
179
  source: DocumentIssueSource.VALIDATION,
@@ -30,6 +30,12 @@ export interface GeneratorTestOptions<SERVICES, SHARED_SERVICES, MODEL extends A
30
30
  generateForWorkspace?: (service: DslServices<SERVICES, SHARED_SERVICES>, documents: LangiumDocument<AstNode>[], workspaceFolder: WorkspaceFolder, targets?: GeneratorTarget[]) => Promise<GeneratedContentManager>;
31
31
  generateForModel?: (services: ExtractServiceType<SERVICES>, document: MODEL, generatorOutput: GeneratorManager) => Promise<void>;
32
32
  }
33
+ /**
34
+ * Vitest title for one workspace.
35
+ * The `(generating)` suffix is only present in generate mode.
36
+ * `GeneratorMode.Generate` is `0`, so the mode must be compared by value.
37
+ */
38
+ export declare function generatorWorkspaceTestName(testDirName: string, generateMode: GeneratorMode): string;
33
39
  /**
34
40
  * Run generator snapshot tests for all workspaces (subdirectories of the `testSuiteDir` directory).
35
41
  * For each workspace there will be a tests added to vitest suite.
@@ -13,6 +13,15 @@ export var GeneratorMode;
13
13
  })(GeneratorMode || (GeneratorMode = {}));
14
14
  ;
15
15
  const globalGenerateMode = process.env.GENERATOR_TEST === "generate" ? GeneratorMode.Generate : GeneratorMode.Verify;
16
+ /**
17
+ * Vitest title for one workspace.
18
+ * The `(generating)` suffix is only present in generate mode.
19
+ * `GeneratorMode.Generate` is `0`, so the mode must be compared by value.
20
+ */
21
+ export function generatorWorkspaceTestName(testDirName, generateMode) {
22
+ const suffix = generateMode === GeneratorMode.Generate ? ' (generating)' : '';
23
+ return `DSL-Workspace "${testDirName}"${suffix}`;
24
+ }
16
25
  /**
17
26
  * Run generator snapshot tests for all workspaces (subdirectories of the `testSuiteDir` directory).
18
27
  * For each workspace there will be a tests added to vitest suite.
@@ -27,7 +36,7 @@ export function langiumGeneratorSuite(testSuiteDir, options, targets) {
27
36
  .filter((dirent) => dirent.isDirectory())
28
37
  .forEach((dirent) => {
29
38
  const testDirName = dirent.name;
30
- test(`DSL-Workspace "${testDirName}"${generateMode ? ' (generating)' : ''}`, async () => {
39
+ test(generatorWorkspaceTestName(testDirName, generateMode), async () => {
31
40
  await langiumGeneratorTest(path.join(testSuiteDir, testDirName), options, targets);
32
41
  });
33
42
  });
@@ -77,13 +86,21 @@ export async function langiumGeneratorTest(testDir, options, targets) {
77
86
  if (generateMode === GeneratorMode.Generate) {
78
87
  cleanDir(outputDir);
79
88
  for (const { dir, metadataFile, target } of dirsAndTargets) {
89
+ // An empty target has nothing to commit. Git does not keep the empty directory.
90
+ if (generatedContentManager.getGeneratedContent(target.name).size === 0) {
91
+ continue;
92
+ }
80
93
  await generatedContentManager.writeToDisk(dir, target.name);
81
94
  writeMetaData(generatedContentManager, metadataFile, target.name);
82
95
  }
83
96
  }
84
97
  else {
85
98
  for (const { dir, metadataFile, target } of dirsAndTargets) {
86
- verifyFiles(generatedContentManager.getGeneratedContent(target.name), dir, target.name);
99
+ const generatedContent = generatedContentManager.getGeneratedContent(target.name);
100
+ if (generatedContent.size === 0 && !fs.existsSync(dir) && !fs.existsSync(metadataFile)) {
101
+ continue;
102
+ }
103
+ verifyFiles(generatedContent, dir, target.name);
87
104
  verifyMetaData(generatedContentManager, metadataFile, target.name);
88
105
  }
89
106
  }
@@ -166,44 +166,40 @@ export declare function toContainIssue(document: LangiumDocument | ParsedDocumen
166
166
  message: () => string;
167
167
  };
168
168
  /**
169
- * Interface extending Vitest's matchers with Langium-specific assertions.
169
+ * Vitest builds `expect()` from Chai's `Assertion` in every supported line.
170
+ * Vitest's own `Assertion` is `Assertion<T>` before version 5 and `Assertion<R, T>` from 5 on.
171
+ * Those two declarations cannot be merged, so the matchers are added here instead.
170
172
  */
171
- interface LangiumMatchers<R = unknown> {
172
- /**
173
- * Asserts that a document has no errors after parsing.
174
- * Non-error diagnostics (warnings, hints) are ignored by default.
175
- *
176
- * @param parameters - Optional parameters to customize which errors to ignore.
177
- */
178
- toHaveNoErrors: R extends LangiumDocument | ParsedDocument ? (parameters?: IgnoreParameters) => void : never;
179
- /**
180
- * Asserts that a document has no issues after parsing.
181
- *
182
- * @param parameters - Optional parameters to customize which issues to ignore.
183
- */
184
- toHaveNoIssues: R extends LangiumDocument | ParsedDocument ? (parameters?: IgnoreParameters) => void : never;
185
- /**
186
- * Asserts that a parsed document has specific issues at specified markers.
187
- *
188
- * @param expectedIssues - An array of expected issues.
189
- * @param parameters - Optional parameters to customize which issues to ignore.
190
- */
191
- toHaveDocumentIssues: R extends ParsedDocument ? (expectedIssues: Array<IssueExpectation>, parameters?: IgnoreParameters) => void : never;
192
- /**
193
- * Asserts that a document contains a specific issue.
194
- *
195
- * @param expectedIssue - The expected issue to look for.
196
- * @param parameters - Optional parameters to customize which issues to ignore.
197
- */
198
- toContainIssue: R extends LangiumDocument | ParsedDocument ? (expectedIssue: IssueExpectation, parameters?: IgnoreParameters) => void : never;
199
- }
200
- /**
201
- * Augments Vitest's assertion interface with Langium-specific matchers.
202
- */
203
- declare module 'vitest' {
204
- interface Assertion<T> extends LangiumMatchers<T> {
205
- }
206
- interface AsymmetricMatchersContaining<R = unknown> extends LangiumMatchers<R> {
173
+ declare global {
174
+ namespace Chai {
175
+ interface Assertion {
176
+ /**
177
+ * Asserts that a document has no errors after parsing.
178
+ * Non-error diagnostics (warnings, hints) are ignored by default.
179
+ *
180
+ * @param parameters - Optional parameters to customize which errors to ignore.
181
+ */
182
+ toHaveNoErrors(parameters?: IgnoreParameters): void;
183
+ /**
184
+ * Asserts that a document has no issues after parsing.
185
+ *
186
+ * @param parameters - Optional parameters to customize which issues to ignore.
187
+ */
188
+ toHaveNoIssues(parameters?: IgnoreParameters): void;
189
+ /**
190
+ * Asserts that a parsed document has specific issues at specified markers.
191
+ *
192
+ * @param expectedIssues - An array of expected issues.
193
+ * @param parameters - Optional parameters to customize which issues to ignore.
194
+ */
195
+ toHaveDocumentIssues(expectedIssues: Array<IssueExpectation>, parameters?: IgnoreParameters): void;
196
+ /**
197
+ * Asserts that a document contains a specific issue.
198
+ *
199
+ * @param expectedIssue - The expected issue to look for.
200
+ * @param parameters - Optional parameters to customize which issues to ignore.
201
+ */
202
+ toContainIssue(expectedIssue: IssueExpectation, parameters?: IgnoreParameters): void;
203
+ }
207
204
  }
208
205
  }
209
- export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "langium-tools",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "A set of tools for Langium",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -39,7 +39,7 @@
39
39
  "langium": "^4.4.2"
40
40
  },
41
41
  "peerDependencies": {
42
- "vitest": "~2.0.5"
42
+ "vitest": "^2.1.9 || ^3.2.6 || >=4.1.0"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@eslint/js": "^9.8.0",
@@ -49,7 +49,7 @@
49
49
  "typedoc-plugin-markdown": "^3.0.0",
50
50
  "typescript": "~5.8.3",
51
51
  "typescript-eslint": "^7.18.0",
52
- "vitest": "~2.0.5"
52
+ "vitest": "^5.1.1"
53
53
  },
54
54
  "overrides": {
55
55
  "eslint": "^9.8.0"
@@ -1,6 +1,6 @@
1
1
  import "./string.js";
2
2
  import { LangiumDocument } from "langium";
3
- import { DiagnosticSeverity, MarkupContent } from "vscode-languageserver";
3
+ import { Diagnostic, DiagnosticSeverity, MarkupContent } from "vscode-languageserver";
4
4
  import type { IToken } from 'chevrotain';
5
5
  import { EOL } from "node:os";
6
6
 
@@ -139,6 +139,83 @@ function diagnosticMessage(message: string | MarkupContent): string {
139
139
  return typeof message === 'string' ? message : message.value;
140
140
  }
141
141
 
142
+ /** Codes Langium's `DocumentValidator` stores on copied lexer and parser diagnostics. */
143
+ const LEXING_ERROR = "lexing-error";
144
+ const PARSING_ERROR = "parsing-error";
145
+
146
+ function diagnosticCode(diagnostic: Diagnostic): string | undefined {
147
+ const data = diagnostic.data;
148
+ if (typeof data !== "object" || data === null || !("code" in data)) {
149
+ return undefined;
150
+ }
151
+ const code = (data as { code?: unknown }).code;
152
+ return typeof code === "string" ? code : undefined;
153
+ }
154
+
155
+ function syntaxSource(diagnostic: Diagnostic): DocumentIssueSource.LEXER | DocumentIssueSource.PARSER | undefined {
156
+ const code = diagnosticCode(diagnostic);
157
+ if (code === LEXING_ERROR) {
158
+ return DocumentIssueSource.LEXER;
159
+ }
160
+ if (code === PARSING_ERROR) {
161
+ return DocumentIssueSource.PARSER;
162
+ }
163
+ return undefined;
164
+ }
165
+
166
+ /**
167
+ * Langium copies each lexer and parser error into `document.diagnostics` after validation.
168
+ * Prefer that copy: its range has an end position. Keep the offset from `parseResult`.
169
+ * A `parseResult` error with no matching diagnostic is kept as it is.
170
+ */
171
+ function mergeSyntaxErrors<T>(
172
+ errors: readonly T[],
173
+ diagnostics: readonly Diagnostic[],
174
+ source: DocumentIssueSource,
175
+ fromParseResult: (error: T) => DocumentIssue,
176
+ messageOf: (error: T) => string,
177
+ ): DocumentIssue[] {
178
+ const issues: DocumentIssue[] = [];
179
+ const used = new Set<number>();
180
+ for (const error of errors) {
181
+ const message = messageOf(error);
182
+ const match = diagnostics.findIndex((diagnostic, index) =>
183
+ !used.has(index) && diagnosticMessage(diagnostic.message) === message
184
+ );
185
+ const parsed = fromParseResult(error);
186
+ if (match >= 0) {
187
+ used.add(match);
188
+ const diagnostic = diagnostics[match];
189
+ issues.push({
190
+ source,
191
+ severity: mapSeverity(diagnostic.severity),
192
+ message: diagnosticMessage(diagnostic.message),
193
+ startOffset: parsed.startOffset,
194
+ startLine: diagnostic.range.start.line,
195
+ startColumn: diagnostic.range.start.character,
196
+ endLine: diagnostic.range.end.line,
197
+ endColumn: diagnostic.range.end.character,
198
+ });
199
+ } else {
200
+ issues.push(parsed);
201
+ }
202
+ }
203
+ diagnostics.forEach((diagnostic, index) => {
204
+ if (!used.has(index)) {
205
+ issues.push({
206
+ source,
207
+ severity: mapSeverity(diagnostic.severity),
208
+ message: diagnosticMessage(diagnostic.message),
209
+ startLine: diagnostic.range.start.line,
210
+ startColumn: diagnostic.range.start.character,
211
+ endLine: diagnostic.range.end.line,
212
+ endColumn: diagnostic.range.end.character,
213
+ });
214
+ }
215
+ });
216
+ return issues;
217
+ }
218
+
142
219
  function mapSeverity(severity?: DiagnosticSeverity): DocumentIssueSeverity {
143
220
  if (!severity) {
144
221
  return DocumentIssueSeverity.UNKNOWN;
@@ -180,43 +257,52 @@ export function getDocumentIssues(
180
257
  skipValidation = false,
181
258
  } = params || {};
182
259
 
260
+ const diagnostics = document.diagnostics ?? [];
183
261
  const issues: DocumentIssue[] = [];
184
262
  if (!skipLexerErrors) {
185
- document.parseResult.lexerErrors.forEach((lexerIssue) => {
186
- issues.push({
263
+ issues.push(...mergeSyntaxErrors(
264
+ document.parseResult.lexerErrors,
265
+ diagnostics.filter((diagnostic) => syntaxSource(diagnostic) === DocumentIssueSource.LEXER),
266
+ DocumentIssueSource.LEXER,
267
+ (lexerIssue) => ({
187
268
  source: DocumentIssueSource.LEXER,
188
269
  message: lexerIssue.message,
189
270
  severity: DocumentIssueSeverity.ERROR,
190
271
  startOffset: lexerIssue.offset,
191
272
  startLine: plus(lexerIssue.line, -1),
192
273
  startColumn: plus(lexerIssue.column, -1),
193
- });
194
- });
274
+ }),
275
+ (lexerIssue) => lexerIssue.message,
276
+ ));
195
277
  }
196
278
 
197
279
  if (!skipParserErrors) {
198
- document.parseResult.parserErrors.forEach((parserError) => {
199
- // Chevrotain exposes the token before the failure. Inserted EOF tokens use -1
200
- // for offset, line, and column, which is not a real position.
201
- const previousToken = (parserError as unknown as { previousToken: IToken })?.previousToken as IToken;
202
- issues.push({
203
- source: DocumentIssueSource.PARSER,
204
- severity: DocumentIssueSeverity.ERROR,
205
- message: parserError.message,
206
- startOffset: firstDefinedNumber(parserError.token.startOffset, previousToken?.startOffset),
207
- startLine: plus(firstDefinedNumber(parserError.token.startLine, previousToken?.startLine), -1),
208
- startColumn: plus(firstDefinedNumber(parserError.token.startColumn, previousToken?.startColumn), -1),
209
-
210
- // Unrelieable end position returned by Chevrotain (24.09.2024)
211
- // endOffset: firstDefinedNumber(parserError.token.endOffset, previousToken?.endOffset),
212
- // endLine: plus(firstDefinedNumber(parserError.token.endLine, previousToken?.endLine), -1),
213
- // endColumn: plus(firstDefinedNumber(parserError.token.endColumn, previousToken?.endColumn), 1),
214
- });
215
- });
280
+ issues.push(...mergeSyntaxErrors(
281
+ document.parseResult.parserErrors,
282
+ diagnostics.filter((diagnostic) => syntaxSource(diagnostic) === DocumentIssueSource.PARSER),
283
+ DocumentIssueSource.PARSER,
284
+ (parserError) => {
285
+ // Chevrotain exposes the token before the failure. Inserted EOF tokens use -1
286
+ // for offset, line, and column, which is not a real position.
287
+ const previousToken = (parserError as unknown as { previousToken: IToken })?.previousToken as IToken;
288
+ return {
289
+ source: DocumentIssueSource.PARSER,
290
+ severity: DocumentIssueSeverity.ERROR,
291
+ message: parserError.message,
292
+ startOffset: firstDefinedNumber(parserError.token.startOffset, previousToken?.startOffset),
293
+ startLine: plus(firstDefinedNumber(parserError.token.startLine, previousToken?.startLine), -1),
294
+ startColumn: plus(firstDefinedNumber(parserError.token.startColumn, previousToken?.startColumn), -1),
295
+ };
296
+ },
297
+ (parserError) => parserError.message,
298
+ ));
216
299
  }
217
300
 
218
301
  if (!skipValidation) {
219
- document.diagnostics?.forEach((diagnostic) => {
302
+ diagnostics.forEach((diagnostic) => {
303
+ if (syntaxSource(diagnostic)) {
304
+ return;
305
+ }
220
306
  if (!skipNonErrorDiagnostics || diagnostic.severity === DiagnosticSeverity.Error) {
221
307
  issues.push({
222
308
  source: DocumentIssueSource.VALIDATION,
@@ -65,6 +65,16 @@ export interface GeneratorTestOptions<SERVICES, SHARED_SERVICES, MODEL extends A
65
65
 
66
66
  const globalGenerateMode = process.env.GENERATOR_TEST === "generate" ? GeneratorMode.Generate : GeneratorMode.Verify;
67
67
 
68
+ /**
69
+ * Vitest title for one workspace.
70
+ * The `(generating)` suffix is only present in generate mode.
71
+ * `GeneratorMode.Generate` is `0`, so the mode must be compared by value.
72
+ */
73
+ export function generatorWorkspaceTestName(testDirName: string, generateMode: GeneratorMode): string {
74
+ const suffix = generateMode === GeneratorMode.Generate ? ' (generating)' : '';
75
+ return `DSL-Workspace "${testDirName}"${suffix}`;
76
+ }
77
+
68
78
  /**
69
79
  * Run generator snapshot tests for all workspaces (subdirectories of the `testSuiteDir` directory).
70
80
  * For each workspace there will be a tests added to vitest suite.
@@ -80,7 +90,7 @@ export function langiumGeneratorSuite<SERVICES, SHARED_SERVICES, MODEL extends A
80
90
  .forEach((dirent) => {
81
91
  const testDirName = dirent.name;
82
92
 
83
- test(`DSL-Workspace "${testDirName}"${generateMode ? ' (generating)' : ''}`, async () => {
93
+ test(generatorWorkspaceTestName(testDirName, generateMode), async () => {
84
94
  await langiumGeneratorTest<SERVICES, SHARED_SERVICES, MODEL>(path.join(testSuiteDir, testDirName), options, targets);
85
95
  });
86
96
  });
@@ -143,12 +153,20 @@ export async function langiumGeneratorTest<SERVICES, SHARED_SERVICES, MODEL exte
143
153
  if (generateMode === GeneratorMode.Generate) {
144
154
  cleanDir(outputDir);
145
155
  for (const { dir, metadataFile, target } of dirsAndTargets) {
156
+ // An empty target has nothing to commit. Git does not keep the empty directory.
157
+ if (generatedContentManager.getGeneratedContent(target.name).size === 0) {
158
+ continue;
159
+ }
146
160
  await generatedContentManager.writeToDisk(dir, target.name);
147
161
  writeMetaData(generatedContentManager, metadataFile, target.name);
148
162
  }
149
163
  } else {
150
164
  for (const { dir, metadataFile, target } of dirsAndTargets) {
151
- verifyFiles(generatedContentManager.getGeneratedContent(target.name), dir, target.name);
165
+ const generatedContent = generatedContentManager.getGeneratedContent(target.name);
166
+ if (generatedContent.size === 0 && !fs.existsSync(dir) && !fs.existsSync(metadataFile)) {
167
+ continue;
168
+ }
169
+ verifyFiles(generatedContent, dir, target.name);
152
170
  verifyMetaData(generatedContentManager, metadataFile, target.name);
153
171
  }
154
172
  }
@@ -411,61 +411,72 @@ expect.extend({
411
411
  });
412
412
 
413
413
  /**
414
- * Interface extending Vitest's matchers with Langium-specific assertions.
414
+ * Vitest builds `expect()` from Chai's `Assertion` in every supported line.
415
+ * Vitest's own `Assertion` is `Assertion<T>` before version 5 and `Assertion<R, T>` from 5 on.
416
+ * Those two declarations cannot be merged, so the matchers are added here instead.
415
417
  */
416
- interface LangiumMatchers<R = unknown> {
417
- /**
418
- * Asserts that a document has no errors after parsing.
419
- * Non-error diagnostics (warnings, hints) are ignored by default.
420
- *
421
- * @param parameters - Optional parameters to customize which errors to ignore.
422
- */
423
- toHaveNoErrors: R extends LangiumDocument | ParsedDocument
424
- ? (parameters?: IgnoreParameters) => void
425
- : never;
426
-
427
- /**
428
- * Asserts that a document has no issues after parsing.
429
- *
430
- * @param parameters - Optional parameters to customize which issues to ignore.
431
- */
432
- toHaveNoIssues: R extends LangiumDocument | ParsedDocument
433
- ? (parameters?: IgnoreParameters) => void
434
- : never;
435
-
436
- /**
437
- * Asserts that a parsed document has specific issues at specified markers.
438
- *
439
- * @param expectedIssues - An array of expected issues.
440
- * @param parameters - Optional parameters to customize which issues to ignore.
441
- */
442
- toHaveDocumentIssues: R extends ParsedDocument
443
- ? (
444
- expectedIssues: Array<IssueExpectation>,
445
- parameters?: IgnoreParameters
446
- ) => void
447
- : never;
448
-
449
- /**
450
- * Asserts that a document contains a specific issue.
451
- *
452
- * @param expectedIssue - The expected issue to look for.
453
- * @param parameters - Optional parameters to customize which issues to ignore.
454
- */
455
- toContainIssue: R extends LangiumDocument | ParsedDocument
456
- ? (expectedIssue: IssueExpectation, parameters?: IgnoreParameters) => void
457
- : never;
418
+ declare global {
419
+ // Chai publishes this surface as a global namespace. Vitest copies it onto `expect()`.
420
+ // eslint-disable-next-line @typescript-eslint/no-namespace
421
+ namespace Chai {
422
+ interface Assertion {
423
+ /**
424
+ * Asserts that a document has no errors after parsing.
425
+ * Non-error diagnostics (warnings, hints) are ignored by default.
426
+ *
427
+ * @param parameters - Optional parameters to customize which errors to ignore.
428
+ */
429
+ toHaveNoErrors(parameters?: IgnoreParameters): void;
430
+
431
+ /**
432
+ * Asserts that a document has no issues after parsing.
433
+ *
434
+ * @param parameters - Optional parameters to customize which issues to ignore.
435
+ */
436
+ toHaveNoIssues(parameters?: IgnoreParameters): void;
437
+
438
+ /**
439
+ * Asserts that a parsed document has specific issues at specified markers.
440
+ *
441
+ * @param expectedIssues - An array of expected issues.
442
+ * @param parameters - Optional parameters to customize which issues to ignore.
443
+ */
444
+ toHaveDocumentIssues(
445
+ expectedIssues: Array<IssueExpectation>,
446
+ parameters?: IgnoreParameters
447
+ ): void;
448
+
449
+ /**
450
+ * Asserts that a document contains a specific issue.
451
+ *
452
+ * @param expectedIssue - The expected issue to look for.
453
+ * @param parameters - Optional parameters to customize which issues to ignore.
454
+ */
455
+ toContainIssue(expectedIssue: IssueExpectation, parameters?: IgnoreParameters): void;
456
+ }
457
+ }
458
458
  }
459
459
 
460
+ type AssertTrue<T extends true> = T;
461
+ type ExpectOf<T> = typeof expect extends (value: T) => infer R ? R : never;
462
+
460
463
  /**
461
- * Augments Vitest's assertion interface with Langium-specific matchers.
464
+ * Fails the build when Vitest stops copying these Chai methods onto `expect()`.
462
465
  */
463
- declare module 'vitest' {
464
-
465
- interface Assertion<T> extends LangiumMatchers<T> { }
466
-
467
- interface AsymmetricMatchersContaining<R = unknown> extends LangiumMatchers<R> { }
468
- }
466
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
467
+ type _LangiumMatchersOnExpect = AssertTrue<
468
+ ExpectOf<LangiumDocument> extends {
469
+ toHaveNoErrors(parameters?: IgnoreParameters): void;
470
+ toHaveNoIssues(parameters?: IgnoreParameters): void;
471
+ toContainIssue(expectedIssue: IssueExpectation, parameters?: IgnoreParameters): void;
472
+ }
473
+ ? ExpectOf<ParsedDocument> extends {
474
+ toHaveDocumentIssues(expectedIssues: Array<IssueExpectation>, parameters?: IgnoreParameters): void;
475
+ }
476
+ ? true
477
+ : false
478
+ : false
479
+ >;
469
480
 
470
481
  /**
471
482
  * Converts an issue expectation into a readable string representation.