langium-tools 0.1.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.
- package/README.md +1171 -0
- package/dist/base/arrays.d.ts +6 -0
- package/dist/base/arrays.js +34 -0
- package/dist/base/document-errors.d.ts +56 -0
- package/dist/base/document-errors.js +198 -0
- package/dist/base/document-issues.d.ts +178 -0
- package/dist/base/document-issues.js +306 -0
- package/dist/base/index.d.ts +4 -0
- package/dist/base/index.js +4 -0
- package/dist/base/marker-parser.d.ts +36 -0
- package/dist/base/marker-parser.js +51 -0
- package/dist/base/string.d.ts +89 -0
- package/dist/base/string.js +104 -0
- package/dist/generator/generated-content-manager.d.ts +207 -0
- package/dist/generator/generated-content-manager.js +242 -0
- package/dist/generator/index.d.ts +2 -0
- package/dist/generator/index.js +2 -0
- package/dist/generator/tools.d.ts +9 -0
- package/dist/generator/tools.js +12 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/lang/index.d.ts +1 -0
- package/dist/lang/index.js +1 -0
- package/dist/lang/java/common.d.ts +1 -0
- package/dist/lang/java/common.js +3 -0
- package/dist/lang/java/generator-tools.d.ts +37 -0
- package/dist/lang/java/generator-tools.js +48 -0
- package/dist/lang/java/import-manager.d.ts +61 -0
- package/dist/lang/java/import-manager.js +88 -0
- package/dist/lang/java/index.d.ts +3 -0
- package/dist/lang/java/index.js +3 -0
- package/dist/testing/common.d.ts +1 -0
- package/dist/testing/common.js +5 -0
- package/dist/testing/generator-testing.d.ts +56 -0
- package/dist/testing/generator-testing.js +184 -0
- package/dist/testing/index.d.ts +4 -0
- package/dist/testing/index.js +4 -0
- package/dist/testing/matchers.d.ts +209 -0
- package/dist/testing/matchers.js +306 -0
- package/dist/testing/parser-tools.d.ts +19 -0
- package/dist/testing/parser-tools.js +18 -0
- package/package.json +59 -0
- package/src/base/arrays.ts +40 -0
- package/src/base/document-issues.ts +430 -0
- package/src/base/index.ts +4 -0
- package/src/base/marker-parser.ts +96 -0
- package/src/base/string.ts +117 -0
- package/src/generator/generated-content-manager.ts +368 -0
- package/src/generator/index.ts +2 -0
- package/src/generator/tools.ts +14 -0
- package/src/index.ts +5 -0
- package/src/lang/index.ts +1 -0
- package/src/lang/java/common.ts +4 -0
- package/src/lang/java/generator-tools.ts +59 -0
- package/src/lang/java/import-manager.ts +98 -0
- package/src/lang/java/index.ts +3 -0
- package/src/testing/common.ts +5 -0
- package/src/testing/generator-testing.ts +266 -0
- package/src/testing/index.ts +4 -0
- package/src/testing/matchers.ts +503 -0
- package/src/testing/parser-tools.ts +34 -0
package/README.md
ADDED
|
@@ -0,0 +1,1171 @@
|
|
|
1
|
+
<a id="readme-top"></a>
|
|
2
|
+
|
|
3
|
+
<!--
|
|
4
|
+
*** I'm using markdown "reference style" links for readability.
|
|
5
|
+
*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
|
|
6
|
+
*** See the bottom of this document for the declaration of the reference variables
|
|
7
|
+
*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
|
|
8
|
+
*** https://www.markdownguide.org/basic-syntax/#reference-style-links
|
|
9
|
+
-->
|
|
10
|
+
|
|
11
|
+
[![Contributors][contributors-shield]][contributors-url]
|
|
12
|
+
[![Forks][forks-shield]][forks-url]
|
|
13
|
+
[![Stargazers][stars-shield]][stars-url]
|
|
14
|
+
[![Issues][issues-shield]][issues-url]
|
|
15
|
+
[![MIT License][license-shield]][license-url]
|
|
16
|
+
|
|
17
|
+
<br />
|
|
18
|
+
<div align="center">
|
|
19
|
+
<!-- TODO
|
|
20
|
+
<a href="https://github.com/borisbrodski/langium-tools">
|
|
21
|
+
<img src="images/logo.png" alt="Logo" width="80" height="80">
|
|
22
|
+
</a>
|
|
23
|
+
-->
|
|
24
|
+
|
|
25
|
+
<h3 align="center">langium-tools</h3>
|
|
26
|
+
|
|
27
|
+
<p align="center">
|
|
28
|
+
A collection of tools for implementing and testing DSLs with <a href="https://langium.org/"><strong>Langium</strong>!</a>
|
|
29
|
+
<br />
|
|
30
|
+
<br />
|
|
31
|
+
<a href="#documentation"><strong>Explore the docs »</strong></a>
|
|
32
|
+
<br />
|
|
33
|
+
<br />
|
|
34
|
+
<a href="https://github.com/borisbrodski/langium-tools/issues/new?labels=bug&template=bug-report---.md">Report Bug</a>
|
|
35
|
+
·
|
|
36
|
+
<a href="https://github.com/borisbrodski/langium-tools/issues/new?labels=enhancement&template=feature-request---.md">Request Feature</a>
|
|
37
|
+
</p>
|
|
38
|
+
</div>
|
|
39
|
+
|
|
40
|
+
<!-- TABLE OF CONTENTS -->
|
|
41
|
+
<ol>
|
|
42
|
+
<li>
|
|
43
|
+
<a href="#about-the-project">About The Project</a>
|
|
44
|
+
<ul>
|
|
45
|
+
<li><a href="#built-with">Built With</a></li>
|
|
46
|
+
</ul>
|
|
47
|
+
</li>
|
|
48
|
+
<li>
|
|
49
|
+
<a href="#getting-started">Getting Started</a>
|
|
50
|
+
<ul>
|
|
51
|
+
<li><a href="#installation">Installation</a></li>
|
|
52
|
+
<li><a href="#example-project">Example project</a></li>
|
|
53
|
+
</ul>
|
|
54
|
+
</li>
|
|
55
|
+
<li>
|
|
56
|
+
<a href="#documentation">Documentation</a>
|
|
57
|
+
<ul>
|
|
58
|
+
<li><a href="#document-issues">Document Issues</a></li>
|
|
59
|
+
<li><a href="#generated-content-manager">Generated Content Manager</a></li>
|
|
60
|
+
<li><a href="#generator-testing-snapshot-testing">Generator Testing (Snapshot Testing)</a></li>
|
|
61
|
+
<li><a href="#vitest-matchers">Vitest Matchers</a></li>
|
|
62
|
+
<li><a href="#miscellaneous">Miscellaneous</a></li>
|
|
63
|
+
<ul>
|
|
64
|
+
<li><a href="#adjusted">`adjusted`</a></li>
|
|
65
|
+
</ul>
|
|
66
|
+
<li><a href="#language-java">Language - Java</a></li>
|
|
67
|
+
</ul>
|
|
68
|
+
</li>
|
|
69
|
+
<li><a href="#roadmap">Roadmap</a></li>
|
|
70
|
+
<li><a href="#contributing">Contributing</a></li>
|
|
71
|
+
<li><a href="#license">License</a></li>
|
|
72
|
+
<li><a href="#contact">Contact</a></li>
|
|
73
|
+
<li><a href="#acknowledgments">Acknowledgments</a></li>
|
|
74
|
+
</ol>
|
|
75
|
+
|
|
76
|
+
<!-- ABOUT THE PROJECT -->
|
|
77
|
+
|
|
78
|
+
## About The Project
|
|
79
|
+
|
|
80
|
+
<!--
|
|
81
|
+
[![Product Name Screen Shot][product-screenshot]](https://example.com)
|
|
82
|
+
-->
|
|
83
|
+
|
|
84
|
+
This project is a collection of tools, that should power up DSL development with Langium:
|
|
85
|
+
|
|
86
|
+
Language features:
|
|
87
|
+
|
|
88
|
+
- <strong>Helper methods</strong> - collection of helper methods, like `.toFirstUpper()`
|
|
89
|
+
- <strong>Generators</strong> - nice framework to generate files from AST (both in memory and on the disk)
|
|
90
|
+
- <strong>Issues</strong> - unified way to access, verify and print out errors and warning in DSLs
|
|
91
|
+
|
|
92
|
+
Testing features:
|
|
93
|
+
|
|
94
|
+
- Advance generator testing framework (optimized for large amount of generated code)
|
|
95
|
+
- `vitest` matchers and tools to test DSL validation
|
|
96
|
+
|
|
97
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
98
|
+
|
|
99
|
+
### Built With
|
|
100
|
+
|
|
101
|
+
This section should list any major frameworks/libraries used to bootstrap your project. Leave any add-ons/plugins for the acknowledgements section. Here are a few examples.
|
|
102
|
+
|
|
103
|
+
- [![Typescript][Typescript]][Typescript-url]
|
|
104
|
+
|
|
105
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
106
|
+
|
|
107
|
+
<!-- GETTING STARTED -->
|
|
108
|
+
|
|
109
|
+
## Getting Started
|
|
110
|
+
|
|
111
|
+
- Add package to your project
|
|
112
|
+
- Start using one or more features it provides
|
|
113
|
+
- Check out example project to see `langium-tools` in action
|
|
114
|
+
|
|
115
|
+
### Installation
|
|
116
|
+
|
|
117
|
+
Add the package to your `package.json`
|
|
118
|
+
|
|
119
|
+
1. Install NPM packages
|
|
120
|
+
```sh
|
|
121
|
+
npm install langium-tools
|
|
122
|
+
```
|
|
123
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
124
|
+
|
|
125
|
+
### Example project
|
|
126
|
+
|
|
127
|
+
You can check out The Umltimative Example: the default langium example project <strong>statemachine</strong> enhanced with all features of `langium-tools`:
|
|
128
|
+
|
|
129
|
+
- TODO - ADD LINK HERE
|
|
130
|
+
|
|
131
|
+
## Documentation
|
|
132
|
+
|
|
133
|
+
See [typedoc documentation](https://borisbrodski.github.io/langium-tools)
|
|
134
|
+
|
|
135
|
+
### Document Issues
|
|
136
|
+
|
|
137
|
+
When working with Langium documents, it's essential to handle and report issues such as syntax errors, validation errors, and other diagnostics in a unified and user-friendly way. The langium-tools package provides utilities to simplify access to document issues from different sources (lexer, parser, validation) and to generate comprehensive summaries of these issues.
|
|
138
|
+
|
|
139
|
+
#### Features
|
|
140
|
+
|
|
141
|
+
- **Unified Issue Access**: Collect all issues from a LangiumDocument, including lexer errors, parser errors, and validation diagnostics.
|
|
142
|
+
- **Customizable Filtering**: Optionally filter issues based on their source or severity.
|
|
143
|
+
- **Issue Summarization**: Generate summaries of issues with counts and formatted messages.
|
|
144
|
+
- **Formatted Issue Strings**: Convert issues into human-readable strings for logging or displaying.
|
|
145
|
+
|
|
146
|
+
#### Getting Issues from a Document
|
|
147
|
+
|
|
148
|
+
To retrieve issues from a LangiumDocument, use the getDocumentIssues function:
|
|
149
|
+
|
|
150
|
+
```typescript
|
|
151
|
+
import { getDocumentIssues } from "langium-tools/base";
|
|
152
|
+
|
|
153
|
+
const issues = getDocumentIssues(document);
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
By default, getDocumentIssues collects all issues from the lexer, parser, and validation phases.
|
|
157
|
+
You can customize which issues to include using the optional parameters:
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
const issues = getDocumentIssues(document, {
|
|
161
|
+
skipNonErrorDiagnostics: true, // Skip warnings, information, hints
|
|
162
|
+
skipLexerErrors: false, // Include lexer errors
|
|
163
|
+
skipParserErrors: false, // Include parser errors
|
|
164
|
+
skipValidation: false, // Include validation issues
|
|
165
|
+
});
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
#### Generating an Issue Summary
|
|
169
|
+
|
|
170
|
+
To get a summary of the issues in a document, use the getDocumentIssueSummary function:
|
|
171
|
+
|
|
172
|
+
```typescript
|
|
173
|
+
import { getDocumentIssueSummary } from "langium-tools/base";
|
|
174
|
+
|
|
175
|
+
const summary = getDocumentIssueSummary(document);
|
|
176
|
+
|
|
177
|
+
console.log(summary.summary); // e.g., "1 lexer error(s), 2 validation error(s)"
|
|
178
|
+
console.log(summary.message);
|
|
179
|
+
/*
|
|
180
|
+
Lexer Errors:
|
|
181
|
+
Error at 3:15 - Unexpected character
|
|
182
|
+
|
|
183
|
+
Validation Diagnostics:
|
|
184
|
+
Error at 5:10 - Undefined reference to 'myVar'
|
|
185
|
+
Warning at 8:5 - Deprecated usage of 'oldFunc'
|
|
186
|
+
|
|
187
|
+
1 lexer error(s), 2 validation issue(s)
|
|
188
|
+
*/
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
The DocumentIssueSummary object contains:
|
|
192
|
+
|
|
193
|
+
- `countTotal`: Total number of issues
|
|
194
|
+
- `countErrors`: Number of issues with severity ERROR
|
|
195
|
+
- `countNonErrors`: Number of issues with severity other than ERROR
|
|
196
|
+
- `summary`: A brief summary string
|
|
197
|
+
- `message`: A detailed message listing all issues
|
|
198
|
+
|
|
199
|
+
#### Converting Issues to Strings
|
|
200
|
+
|
|
201
|
+
You can convert individual issues to formatted strings using documentIssueToString:
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
import { documentIssueToString } from "langium-tools/base";
|
|
205
|
+
|
|
206
|
+
issues.forEach((issue) => {
|
|
207
|
+
const issueStr = documentIssueToString(issue);
|
|
208
|
+
console.log(issueStr);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// Output:
|
|
212
|
+
// Error at 3:15 - Unexpected character
|
|
213
|
+
// Warning at 5:10 - Deprecated usage of 'oldFunc'
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
#### Issue Types and Severities
|
|
217
|
+
|
|
218
|
+
The module defines the following enums for issue sources and severities:
|
|
219
|
+
|
|
220
|
+
**DocumentIssueSource**
|
|
221
|
+
|
|
222
|
+
- `LEXER`: Issues originating from the lexer (tokenization errors).
|
|
223
|
+
- `PARSER`: Issues originating from the parser (syntax errors).
|
|
224
|
+
- `VALIDATION`: Issues originating from validation (semantic errors).
|
|
225
|
+
|
|
226
|
+
**DocumentIssueSeverity**
|
|
227
|
+
|
|
228
|
+
- `ERROR`: Critical issues that prevent further processing.
|
|
229
|
+
- `WARNING`: Issues that may lead to problems but do not prevent processing.
|
|
230
|
+
- `INFORMATION`: Informational messages.
|
|
231
|
+
- `HINT`: Suggestions to improve the document.
|
|
232
|
+
- `UNKNOWN`: Severity is unknown.
|
|
233
|
+
|
|
234
|
+
#### API Reference
|
|
235
|
+
|
|
236
|
+
For detailed API documentation, see the Typedoc documentation.
|
|
237
|
+
|
|
238
|
+
- [getDocumentIssueSummary](https://borisbrodski.github.io/langium-tools/functions/base.getDocumentIssueSummary.html)
|
|
239
|
+
- [getDocumentIssues](https://borisbrodski.github.io/langium-tools/functions/base.getDocumentIssues.html)
|
|
240
|
+
- [documentIssueToString](https://borisbrodski.github.io/langium-tools/functions/base.documentIssueToString.html)
|
|
241
|
+
- [DocumentIssue](https://borisbrodski.github.io/langium-tools/types/base.DocumentIssue.html)
|
|
242
|
+
- [DocumentIssueSummary](https://borisbrodski.github.io/langium-tools/types/base.DocumentIssueSummary.html)
|
|
243
|
+
- [DocumentIssueSource](https://borisbrodski.github.io/langium-tools/enums/base.DocumentIssueSource.html)
|
|
244
|
+
- [DocumentIssueSeverity](https://borisbrodski.github.io/langium-tools/enums/base.DocumentIssueSeverity.html)
|
|
245
|
+
|
|
246
|
+
#### Notes
|
|
247
|
+
|
|
248
|
+
- The position information in issues is zero-based for both lines and columns.
|
|
249
|
+
- The utilities handle the potential absence of position data gracefully.
|
|
250
|
+
- Ensure that you have imported the necessary functions from langium-tools in your project.
|
|
251
|
+
|
|
252
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
253
|
+
|
|
254
|
+
### Generated Content Manager
|
|
255
|
+
|
|
256
|
+
The `GeneratedContentManager` class provides a unified API for code generation in Langium projects. It allows you to collect generated files in memory, manage multiple output targets, and write the generated content to the filesystem. This is especially useful for snapshot testing, where you can compare the in-memory generated content against saved snapshots to ensure no unintended changes have occurred.
|
|
257
|
+
|
|
258
|
+
#### Features
|
|
259
|
+
|
|
260
|
+
- **Unified Generator API**: Simplify code generation with a consistent interface.
|
|
261
|
+
- **In-Memory Generation**: Collect generated files in memory for flexible processing.
|
|
262
|
+
- **Initial Generation**: Don't overwrite existing files.
|
|
263
|
+
- **Preserve File Timestamp**: File will be overwritten only if the content has actually changed.
|
|
264
|
+
- **Multiple Targets**: Support multiple output directories (targets) with custom overwrite settings.
|
|
265
|
+
- **Snapshot Testing Support**: Facilitate testing by comparing in-memory generated content with committed snapshots.
|
|
266
|
+
|
|
267
|
+
#### Getting Started with GeneratedContentManager
|
|
268
|
+
|
|
269
|
+
To use the `GeneratedContentManager`, you need to:
|
|
270
|
+
|
|
271
|
+
1. Create an instance of `GeneratedContentManager`, optionally providing a list of workspace URIs.
|
|
272
|
+
2. Generate content for your models using `GeneratorManager`.
|
|
273
|
+
3. Write the generated content to disk using `writeToDisk`.
|
|
274
|
+
|
|
275
|
+
##### Example Usage
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
import { GeneratedContentManager } from "langium-tools/generator";
|
|
279
|
+
|
|
280
|
+
// Create a new manager
|
|
281
|
+
const manager = new GeneratedContentManager(optionalListOfWorkspaceURIs);
|
|
282
|
+
|
|
283
|
+
// Generate content for multiple models
|
|
284
|
+
generator(manager.generatorManagerFor(model1));
|
|
285
|
+
generator(manager.generatorManagerFor(model2));
|
|
286
|
+
|
|
287
|
+
// Write the generated content to disk
|
|
288
|
+
await manager.writeToDisk("./generated");
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
##### Implementing a Generator Function
|
|
292
|
+
|
|
293
|
+
Here's how you might implement a generator function using `GeneratorManager`:
|
|
294
|
+
|
|
295
|
+
```typescript
|
|
296
|
+
function generator(manager: GeneratorManager) {
|
|
297
|
+
const model = manager.getModel();
|
|
298
|
+
const document = manager.getDocument();
|
|
299
|
+
const workspaceURI = manager.getWorkspaceURI();
|
|
300
|
+
const localPath = manager.getDocumentLocalPath();
|
|
301
|
+
|
|
302
|
+
// Generate files
|
|
303
|
+
manager.createFile(
|
|
304
|
+
"src-gen/abstract_process.ts",
|
|
305
|
+
"// Generated by Langium. Do not edit.",
|
|
306
|
+
);
|
|
307
|
+
manager.createFile("src/process.ts", "// Initially generated by Langium", {
|
|
308
|
+
overwrite: false,
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
#### Managing Generated Content
|
|
314
|
+
|
|
315
|
+
The `GeneratedContentManager` allows you to collect and manage generated files before writing them to disk. This can be particularly useful for testing and validation purposes.
|
|
316
|
+
|
|
317
|
+
##### Creating Files
|
|
318
|
+
|
|
319
|
+
Use the `createFile` method of `GeneratorManager` to add files to the generated content:
|
|
320
|
+
|
|
321
|
+
```typescript
|
|
322
|
+
manager.createFile(filePath: string, content: string, options?: CreateFileOptions);
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
- `filePath`: The relative path to the file within the output directory.
|
|
326
|
+
- `content`: The content to be written to the file.
|
|
327
|
+
- `options`: Optional settings, such as overwrite and target.
|
|
328
|
+
|
|
329
|
+
##### Overwrite Behavior
|
|
330
|
+
|
|
331
|
+
By default, files are overwritten when written to disk. You can control this behavior using the `overwrite` option:
|
|
332
|
+
|
|
333
|
+
```typescript
|
|
334
|
+
manager.createFile("src/process.ts", "// Initially generated by Langium", {
|
|
335
|
+
overwrite: false,
|
|
336
|
+
});
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
#### Working with Targets
|
|
340
|
+
|
|
341
|
+
Targets represent different output directories or configurations. You can define multiple targets with custom settings.
|
|
342
|
+
|
|
343
|
+
Adding a Target
|
|
344
|
+
|
|
345
|
+
```typescript
|
|
346
|
+
manager.addTarget({
|
|
347
|
+
name: "CUSTOM_TARGET",
|
|
348
|
+
overwrite: false,
|
|
349
|
+
});
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
##### Using Targets
|
|
353
|
+
|
|
354
|
+
Specify the target when creating files:
|
|
355
|
+
|
|
356
|
+
```typescript
|
|
357
|
+
manager.createFile("custom.ts", "// Custom target content", {
|
|
358
|
+
target: "CUSTOM_TARGET",
|
|
359
|
+
});
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
##### Writing to Disk
|
|
363
|
+
|
|
364
|
+
After generating content, use writeToDisk to write all collected files to the filesystem:
|
|
365
|
+
|
|
366
|
+
```typescript
|
|
367
|
+
await manager.writeToDisk(outputDir: string, target?: string);
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
- `outputDir`: The directory where files will be written.
|
|
371
|
+
- `target`: Optional target name. If not provided, the default target is used.
|
|
372
|
+
|
|
373
|
+
#### API Reference
|
|
374
|
+
|
|
375
|
+
For detailed API documentation, see the Typedoc documentation.
|
|
376
|
+
|
|
377
|
+
- [GeneratedContentManager](https://borisbrodski.github.io/langium-tools/classes/generator.GeneratedContentManager.html)
|
|
378
|
+
- [GeneratorManager](https://borisbrodski.github.io/langium-tools/interfaces/generator.GeneratorManager.html)
|
|
379
|
+
- [GeneratorTarget](https://borisbrodski.github.io/langium-tools/interfaces/generator.GeneratorTarget.html)
|
|
380
|
+
- [CreateFileOptions](https://borisbrodski.github.io/langium-tools/interfaces/generator.CreateFileOptions.html)
|
|
381
|
+
|
|
382
|
+
#### Notes
|
|
383
|
+
|
|
384
|
+
- **Workspace URIs**: When creating a GeneratedContentManager, you can provide workspace URIs to help determine relative paths for documents.
|
|
385
|
+
- **Conflict Detection**: The manager detects conflicts if the same file is generated multiple times with different content or overwrite settings.
|
|
386
|
+
- **Asynchronous Operations**: Writing to disk is asynchronous and returns a promise.
|
|
387
|
+
|
|
388
|
+
#### Example: Full Workflow
|
|
389
|
+
|
|
390
|
+
```typescript
|
|
391
|
+
import {
|
|
392
|
+
GeneratedContentManager,
|
|
393
|
+
GeneratorManager,
|
|
394
|
+
} from "langium-tools/generator";
|
|
395
|
+
|
|
396
|
+
// Initialize the manager
|
|
397
|
+
const manager = new GeneratedContentManager(["./workspace"]);
|
|
398
|
+
|
|
399
|
+
// Define a generator function
|
|
400
|
+
function generateCode(manager: GeneratorManager) {
|
|
401
|
+
const model = manager.getModel();
|
|
402
|
+
// Generate code based on the model
|
|
403
|
+
manager.createFile("model.ts", `// Code for model ${model.name}`);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// Generate code for models
|
|
407
|
+
const models = [model1, model2];
|
|
408
|
+
models.forEach((model) => {
|
|
409
|
+
const genManager = manager.generatorManagerFor(model);
|
|
410
|
+
generateCode(genManager);
|
|
411
|
+
});
|
|
412
|
+
|
|
413
|
+
// Write all generated content to disk
|
|
414
|
+
await manager.writeToDisk("./generated");
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
#### Error Handling
|
|
418
|
+
|
|
419
|
+
The GeneratedContentManager provides informative error messages when conflicts occur or when file operations fail, helping you quickly identify and resolve issues.
|
|
420
|
+
|
|
421
|
+
#### Use Cases
|
|
422
|
+
|
|
423
|
+
- **Modular Code Generation**: Manage code generation for multiple models or modules in a unified way.
|
|
424
|
+
- **Testing Generators**: Use in-memory content collection to test your generators without writing to disk.
|
|
425
|
+
- **Custom Build Pipelines**: Integrate with build systems by controlling when and how generated content is written.
|
|
426
|
+
|
|
427
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
428
|
+
|
|
429
|
+
### Generator Testing (Snapshot Testing)
|
|
430
|
+
|
|
431
|
+
Testing code generators is crucial to ensure that changes in your generator logic do not introduce unintended side effects. The `langium-tools` package provides utilities for generator snapshot testing, allowing you to verify that your generators produce the expected output over time.
|
|
432
|
+
|
|
433
|
+
#### Overview
|
|
434
|
+
|
|
435
|
+
The main idea is to:
|
|
436
|
+
|
|
437
|
+
- **Commit generated content** to your version control system (e.g., Git).
|
|
438
|
+
- **Run tests in verify mode** to ensure generators have not changed unintentionally.
|
|
439
|
+
- **Approve changes** by regenerating snapshots and reviewing diffs when intentional changes are made.
|
|
440
|
+
|
|
441
|
+
#### Features
|
|
442
|
+
|
|
443
|
+
- **Automated Generator Tests**: Run tests across multiple DSL workspaces to verify generator output.
|
|
444
|
+
- **Snapshot Verification**: Compare in-memory generated content against committed snapshots.
|
|
445
|
+
- **Flexible Modes**: Switch between generate mode (to update snapshots) and verify mode (to validate output).
|
|
446
|
+
|
|
447
|
+
#### Getting Started with Generator Testing
|
|
448
|
+
|
|
449
|
+
To use generator testing utilities, you need to:
|
|
450
|
+
|
|
451
|
+
1. Define generator test options.
|
|
452
|
+
2. Set up test suites using langiumGeneratorSuite.
|
|
453
|
+
3. Configure your test scripts to handle generate and verify modes.
|
|
454
|
+
|
|
455
|
+
Example Usage
|
|
456
|
+
|
|
457
|
+
```typescript
|
|
458
|
+
// test/generator.test.ts
|
|
459
|
+
import { langiumGeneratorSuite } from "langium-tools/testing";
|
|
460
|
+
import { createMyDslServices } from "../src/language/my-dsl-module";
|
|
461
|
+
import { generate } from "../src/cli/generator";
|
|
462
|
+
|
|
463
|
+
describe("Langium code generator tests", () => {
|
|
464
|
+
langiumGeneratorSuite("./test-workspaces", {
|
|
465
|
+
createServices: () => createMyDslServices,
|
|
466
|
+
generateForModel: generate,
|
|
467
|
+
});
|
|
468
|
+
});
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
#### Defining Generator Test Options
|
|
472
|
+
|
|
473
|
+
The `GeneratorTestOptions` interface allows you to specify how the generator tests should run:
|
|
474
|
+
|
|
475
|
+
- `createServices`: Function to create your language services.
|
|
476
|
+
- `initWorkspace`: (Optional) Initialize the workspace.
|
|
477
|
+
- `buildDocuments`: (Optional) Build documents from the workspace.
|
|
478
|
+
- `validateDocuments`: (Optional) Validate the documents before generation.
|
|
479
|
+
- `generateForWorkspace`: (Optional) Custom logic to generate content for the entire workspace.
|
|
480
|
+
- `generateForModel`: Custom logic to generate content for a single model.
|
|
481
|
+
|
|
482
|
+
#### Configuring Test Scripts
|
|
483
|
+
|
|
484
|
+
In your package.json, you can define scripts to run tests in different modes:
|
|
485
|
+
|
|
486
|
+
```json
|
|
487
|
+
{
|
|
488
|
+
"scripts": {
|
|
489
|
+
"test": "GENERATOR_TEST=verify vitest run",
|
|
490
|
+
"test:generate": "GENERATOR_TEST=generate vitest run"
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
- **Verify Mode**: Runs tests to verify that the generator output matches the committed snapshots.
|
|
496
|
+
- **Generate Mode**: Regenerates the snapshots and updates the committed files.
|
|
497
|
+
|
|
498
|
+
#### Writing Generator Tests
|
|
499
|
+
|
|
500
|
+
The `langiumGeneratorSuite` function automatically discovers subdirectories in your test suite directory and runs tests for each DSL workspace.
|
|
501
|
+
|
|
502
|
+
##### Example Directory Structure
|
|
503
|
+
|
|
504
|
+
```
|
|
505
|
+
test-workspaces/
|
|
506
|
+
├── workspace1/
|
|
507
|
+
│ ├── dsls/
|
|
508
|
+
│ │ └── example1.mydsl
|
|
509
|
+
│ └── generated/
|
|
510
|
+
│ └── generated-code.ts
|
|
511
|
+
├── workspace2/
|
|
512
|
+
│ ├── dsls/
|
|
513
|
+
│ │ └── example2.mydsl
|
|
514
|
+
│ └── generated/
|
|
515
|
+
│ └── generated-code.ts
|
|
516
|
+
```
|
|
517
|
+
|
|
518
|
+
#### Running Tests
|
|
519
|
+
|
|
520
|
+
- **Verify Mode**:
|
|
521
|
+
|
|
522
|
+
```bash
|
|
523
|
+
npm test
|
|
524
|
+
```
|
|
525
|
+
|
|
526
|
+
Ensures that the generator output matches the committed `generated` directories.
|
|
527
|
+
|
|
528
|
+
- **Generate Mode**:
|
|
529
|
+
|
|
530
|
+
```bash
|
|
531
|
+
npm run test:generate
|
|
532
|
+
```
|
|
533
|
+
|
|
534
|
+
Updates the `generated` directories with new output from the generators.
|
|
535
|
+
|
|
536
|
+
#### Approving Changes
|
|
537
|
+
|
|
538
|
+
When you intentionally change your generator logic, you can:
|
|
539
|
+
|
|
540
|
+
1. Run `npm run test:generate` to regenerate the output.
|
|
541
|
+
2. Review the changes using `git diff`.
|
|
542
|
+
3. Commit the updated generated content to approve the changes.
|
|
543
|
+
|
|
544
|
+
#### Under the Hood
|
|
545
|
+
|
|
546
|
+
The generator testing utilities work by:
|
|
547
|
+
|
|
548
|
+
- Collecting generated content in memory using `GeneratedContentManager`.
|
|
549
|
+
- Writing the generated content to disk in generate mode.
|
|
550
|
+
- Comparing the in-memory content against the committed files in verify mode.
|
|
551
|
+
|
|
552
|
+
#### API Reference
|
|
553
|
+
|
|
554
|
+
For detailed API documentation, see the [Typedoc documentation](https://borisbrodski.github.io/langium-tools).
|
|
555
|
+
|
|
556
|
+
- [langiumGeneratorSuite](https://borisbrodski.github.io/langium-tools/functions/testing.langiumGeneratorSuite.html)
|
|
557
|
+
- [GeneratorTestOptions](https://borisbrodski.github.io/langium-tools/interfaces/testing.GeneratorTestOptions.html)
|
|
558
|
+
- [GeneratedContentManager](https://borisbrodski.github.io/langium-tools/classes/generator.GeneratedContentManager.html)
|
|
559
|
+
|
|
560
|
+
#### Notes
|
|
561
|
+
|
|
562
|
+
- **Environment Variable**: The `GENERATOR_TEST` environment variable controls the test mode (`verify` or `generate`).
|
|
563
|
+
- **Testing Framework**: The examples use `vitest`, but the utilities can be used with any testing framework, if you are not using automatic workspace discovery, but rather define one test for one workspace using [langiumGeneratorTest](https://borisbrodski.github.io/langium-tools/functions/testing.langiumGeneratorTest.html).
|
|
564
|
+
|
|
565
|
+
#### Example Workflow
|
|
566
|
+
|
|
567
|
+
1. Initial Setup:
|
|
568
|
+
|
|
569
|
+
- Write your generator logic.
|
|
570
|
+
- Run `npm run test:generate` to generate initial snapshots.
|
|
571
|
+
- Commit the `generated` directories to your version control system.
|
|
572
|
+
|
|
573
|
+
2. Continuous Testing:
|
|
574
|
+
|
|
575
|
+
- Run `npm test` during development to ensure your generators produce consistent output.
|
|
576
|
+
|
|
577
|
+
3. Updating Generators:
|
|
578
|
+
|
|
579
|
+
- Make changes to your generator logic.
|
|
580
|
+
- Run `npm test` to see if tests fail (they should if output changes).
|
|
581
|
+
- Run `npm run test:generate` to update the snapshots.
|
|
582
|
+
- Review changes with `git diff`.
|
|
583
|
+
- Commit the changes to approve them.
|
|
584
|
+
|
|
585
|
+
#### Additional Configuration
|
|
586
|
+
|
|
587
|
+
You can customize the behavior by providing custom implementations for optional functions in `GeneratorTestOptions`:
|
|
588
|
+
|
|
589
|
+
- `initWorkspace`: Customize how the workspace is initialized.
|
|
590
|
+
- `buildDocuments`: Control how documents are built from the workspace.
|
|
591
|
+
- `validateDocuments`: Implement custom validation logic before generation.
|
|
592
|
+
- `generateForWorkspace`: Generate content at the workspace level instead of per model.
|
|
593
|
+
|
|
594
|
+
#### Example: Custom Validation
|
|
595
|
+
|
|
596
|
+
```typescript
|
|
597
|
+
function customValidateDocuments(services: DslServices<MyDslService, MyDslSharedService>, documents: LangiumDocument<MyModel>[]) {
|
|
598
|
+
documents.forEach((doc) => {
|
|
599
|
+
const issues = getDocumentIssues(doc);
|
|
600
|
+
expect(issues.length).toBe(0);
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
langiumGeneratorSuite("./test-workspaces", {
|
|
605
|
+
createServices: () => createMyDslServices(),
|
|
606
|
+
validateDocuments: customValidateDocuments,
|
|
607
|
+
generateForModel: async (services, model, generatorManager) => {
|
|
608
|
+
// Generator logic
|
|
609
|
+
},
|
|
610
|
+
});
|
|
611
|
+
```
|
|
612
|
+
|
|
613
|
+
#### Error Handling
|
|
614
|
+
|
|
615
|
+
The testing utilities provide detailed error messages when:
|
|
616
|
+
|
|
617
|
+
- Generated files do not match the committed snapshots.
|
|
618
|
+
- Unexpected files are found in the generated directories.
|
|
619
|
+
- Metadata mismatches occur, e.g. `overwrite` flag.
|
|
620
|
+
|
|
621
|
+
Use Cases
|
|
622
|
+
|
|
623
|
+
- **Regression Testing**: Ensure that changes to your generators do not introduce regressions.
|
|
624
|
+
- **Collaboration**: Facilitate code reviews by providing clear diffs of generator output.
|
|
625
|
+
- **Automation**: Integrate into CI/CD pipelines for automated testing.
|
|
626
|
+
|
|
627
|
+
#### Conclusion
|
|
628
|
+
|
|
629
|
+
Generator snapshot testing is a powerful technique to maintain the integrity of your code generators. By integrating these testing utilities into your workflow, you can confidently evolve your generators while ensuring consistent output.
|
|
630
|
+
|
|
631
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
632
|
+
|
|
633
|
+
### Vitest Matchers
|
|
634
|
+
|
|
635
|
+
The `langium-tools` package provides custom Vitest matchers to facilitate testing Langium documents and DSLs. These matchers help you assert that your parsers, validators, and other language services behave as expected. They allow you to check for specific issues, errors, and diagnostics in a clean and expressive way.
|
|
636
|
+
|
|
637
|
+
#### Features
|
|
638
|
+
|
|
639
|
+
- Custom Matchers: Extend Vitest's `expect` function with Langium-specific assertions.
|
|
640
|
+
- Issue Assertions: Assert the presence or absence of specific issues in a document.
|
|
641
|
+
- Marker-Based Testing: Use markers in your DSL code to pinpoint locations for expected issues.
|
|
642
|
+
- Flexible Ignoring: Customize which types of issues (lexer, parser, validation) to include or ignore in your assertions.
|
|
643
|
+
|
|
644
|
+
#### Getting Started with Vitest Matchers
|
|
645
|
+
|
|
646
|
+
To use the Vitest matchers, you need to:
|
|
647
|
+
|
|
648
|
+
1. Import the matchers in your test files.
|
|
649
|
+
2. Parse your DSL code, optionally using markers.
|
|
650
|
+
3. Use the custom matchers in your assertions.
|
|
651
|
+
|
|
652
|
+
##### Importing the Matchers
|
|
653
|
+
|
|
654
|
+
```typescript
|
|
655
|
+
import "langium-tools/testing"; // Ensure matchers are registered
|
|
656
|
+
import { parseHelper } from "langium/test";
|
|
657
|
+
```
|
|
658
|
+
|
|
659
|
+
##### Parsing DSL Code with Markers
|
|
660
|
+
|
|
661
|
+
You can use the `parseWithMarks` function to parse your DSL code and extract markers. Markers are special annotations in your code that help you specify exact locations for expected issues.
|
|
662
|
+
|
|
663
|
+
```typescript
|
|
664
|
+
import { parseWithMarks } from "langium-tools/testing";
|
|
665
|
+
import { adjusted } from "langium-tools/base";
|
|
666
|
+
|
|
667
|
+
const services = createMyDslServices(EmptyFileSystem);
|
|
668
|
+
const doParse = parseHelper<Model>(services.MyStateMachine);
|
|
669
|
+
const parse = (input: string) => doParse(input, { validate: true });
|
|
670
|
+
|
|
671
|
+
// Parse the code with markers
|
|
672
|
+
const parsedDocument = await parseWithMarks(
|
|
673
|
+
parse,
|
|
674
|
+
adjusted`
|
|
675
|
+
statemachine MyStatemachine
|
|
676
|
+
|
|
677
|
+
state [[[UnusedRule]]];
|
|
678
|
+
`,
|
|
679
|
+
"[[[", "]]]",
|
|
680
|
+
);
|
|
681
|
+
```
|
|
682
|
+
|
|
683
|
+
#### Custom Matchers
|
|
684
|
+
|
|
685
|
+
`toHaveNoErrors`
|
|
686
|
+
|
|
687
|
+
Asserts that a Langium document has no errors after parsing. By default, non-error diagnostics (warnings, hints) are ignored.
|
|
688
|
+
|
|
689
|
+
```typescript
|
|
690
|
+
expect(document).toHaveNoErrors();
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
##### Parameters
|
|
694
|
+
|
|
695
|
+
- `parameters` (optional): Customize which types of issues to ignore.
|
|
696
|
+
|
|
697
|
+
##### Example
|
|
698
|
+
|
|
699
|
+
```typescript
|
|
700
|
+
test("document has no errors", async () => {
|
|
701
|
+
const document = await parse("validCode");
|
|
702
|
+
expect(document).toHaveNoErrors();
|
|
703
|
+
});
|
|
704
|
+
```
|
|
705
|
+
|
|
706
|
+
`toHaveNoIssues`
|
|
707
|
+
|
|
708
|
+
Asserts that a Langium document has no issues (errors, warnings, hints) after parsing.
|
|
709
|
+
|
|
710
|
+
```typescript
|
|
711
|
+
expect(document).toHaveNoIssues();
|
|
712
|
+
```
|
|
713
|
+
|
|
714
|
+
##### Parameters
|
|
715
|
+
|
|
716
|
+
- `parameters` (optional): Customize which types of issues to ignore.
|
|
717
|
+
|
|
718
|
+
##### Example
|
|
719
|
+
|
|
720
|
+
```typescript
|
|
721
|
+
test("document has no issues", async () => {
|
|
722
|
+
const document = await parse("validCode");
|
|
723
|
+
expect(document).toHaveNoIssues();
|
|
724
|
+
});
|
|
725
|
+
```
|
|
726
|
+
|
|
727
|
+
`toHaveDocumentIssues`
|
|
728
|
+
|
|
729
|
+
Asserts that a parsed document with markers has specific issues at specified markers.
|
|
730
|
+
|
|
731
|
+
```typescript
|
|
732
|
+
expect(parsedDocument).toHaveDocumentIssues(expectedIssues, parameters?);
|
|
733
|
+
```
|
|
734
|
+
|
|
735
|
+
##### Parameters
|
|
736
|
+
|
|
737
|
+
- `expectedIssues`: An array of issue expectations.
|
|
738
|
+
- `parameters` (optional): Customize which types of issues to ignore.
|
|
739
|
+
|
|
740
|
+
##### IssueExpectation Interface
|
|
741
|
+
|
|
742
|
+
```typescript
|
|
743
|
+
interface IssueExpectation {
|
|
744
|
+
severity?: DocumentIssueSeverity; // Defaults to ERROR
|
|
745
|
+
source?: DocumentIssueSource; // LEXER, PARSER, VALIDATION
|
|
746
|
+
message: string | RegExp; // Expected message
|
|
747
|
+
markerId?: number; // 0-based index of the marker
|
|
748
|
+
}
|
|
749
|
+
```
|
|
750
|
+
|
|
751
|
+
##### Example
|
|
752
|
+
|
|
753
|
+
```typescript
|
|
754
|
+
test("document has expected issues", async () => {
|
|
755
|
+
const dslCode = adjusted`
|
|
756
|
+
grammar MyLanguage
|
|
757
|
+
entry Rule: name=ID;
|
|
758
|
+
[[[UnusedRule]]]: name=ID;
|
|
759
|
+
terminal ID: /\\^?[_a-zA-Z][\\w_]*/;
|
|
760
|
+
`;
|
|
761
|
+
const parsedDocument = await parseWithMarks(parse, dslCode, "[[[", "]]]");
|
|
762
|
+
|
|
763
|
+
expect(parsedDocument).toHaveDocumentIssues([
|
|
764
|
+
{
|
|
765
|
+
source: DocumentIssueSource.VALIDATION,
|
|
766
|
+
severity: DocumentIssueSeverity.WARNING,
|
|
767
|
+
message: "This rule is declared but never referenced.",
|
|
768
|
+
markerId: 0,
|
|
769
|
+
},
|
|
770
|
+
]);
|
|
771
|
+
});
|
|
772
|
+
```
|
|
773
|
+
|
|
774
|
+
`toContainIssue`
|
|
775
|
+
|
|
776
|
+
Asserts that a Langium document contains a specific issue.
|
|
777
|
+
|
|
778
|
+
```typescript
|
|
779
|
+
expect(document).toContainIssue(expectedIssue, parameters?);
|
|
780
|
+
```
|
|
781
|
+
|
|
782
|
+
##### Parameters
|
|
783
|
+
|
|
784
|
+
- `expectedIssue`: The issue expectation.
|
|
785
|
+
- `parameters` (optional): Customize which types of issues to ignore.
|
|
786
|
+
|
|
787
|
+
##### Example
|
|
788
|
+
|
|
789
|
+
```typescript
|
|
790
|
+
test("document contains specific issue", async () => {
|
|
791
|
+
const document = await parse("invalidCode");
|
|
792
|
+
expect(document).toContainIssue({
|
|
793
|
+
message: /Unexpected character/,
|
|
794
|
+
severity: DocumentIssueSeverity.ERROR,
|
|
795
|
+
source: DocumentIssueSource.LEXER,
|
|
796
|
+
});
|
|
797
|
+
});
|
|
798
|
+
```
|
|
799
|
+
|
|
800
|
+
#### Examples
|
|
801
|
+
|
|
802
|
+
##### Asserting No Errors
|
|
803
|
+
|
|
804
|
+
```typescript
|
|
805
|
+
test('document has no errors', async () => {
|
|
806
|
+
const document = await parse('validCode');
|
|
807
|
+
expect(document).toHaveNoErrors();
|
|
808
|
+
});
|
|
809
|
+
```
|
|
810
|
+
|
|
811
|
+
##### Asserting Specific Issues with Markers
|
|
812
|
+
|
|
813
|
+
```typescript
|
|
814
|
+
test('document has expected validation issue at marker', async () => {
|
|
815
|
+
const dslCode = adjusted`
|
|
816
|
+
grammar MyLanguage
|
|
817
|
+
entry Rule: name=ID;
|
|
818
|
+
<<<UnusedRule>>>: name=ID;
|
|
819
|
+
terminal ID: /\\^?[_a-zA-Z][\\w_]*/;
|
|
820
|
+
`;
|
|
821
|
+
const parsedDocument = await parseWithMarks(parse, dslCode, '<<<', '>>>');
|
|
822
|
+
|
|
823
|
+
expect(parsedDocument).toHaveDocumentIssues([
|
|
824
|
+
{
|
|
825
|
+
source: DocumentIssueSource.VALIDATION, // Optional
|
|
826
|
+
severity: DocumentIssueSeverity.WARNING, // Optional
|
|
827
|
+
message: 'This rule is declared but never referenced.',
|
|
828
|
+
markerId: 0, // Optional
|
|
829
|
+
},
|
|
830
|
+
]);
|
|
831
|
+
});
|
|
832
|
+
````
|
|
833
|
+
|
|
834
|
+
##### Asserting Issue Matching Regex
|
|
835
|
+
|
|
836
|
+
```typescript
|
|
837
|
+
test("document contains issue matching regex", async () => {
|
|
838
|
+
const dslCode = adjusted`
|
|
839
|
+
grammar MyLanguage
|
|
840
|
+
entry Rule: <<<name>>> ID;
|
|
841
|
+
terminal ID: /\\^?[_a-zA-Z][\\w_]*/;
|
|
842
|
+
`;
|
|
843
|
+
const parsedDocument = await parseWithMarks(parse, dslCode, "<<<", ">>>");
|
|
844
|
+
|
|
845
|
+
expect(parsedDocument).toContainIssue({
|
|
846
|
+
message: /Could not resolve reference to AbstractRule named '.\*'/,
|
|
847
|
+
markerId: 0,
|
|
848
|
+
});
|
|
849
|
+
});
|
|
850
|
+
```
|
|
851
|
+
|
|
852
|
+
##### Customizing Ignored Issues
|
|
853
|
+
|
|
854
|
+
All matchers accept an optional parameters object to customize which issues to include or ignore in your assertions.
|
|
855
|
+
|
|
856
|
+
```typescript
|
|
857
|
+
interface IgnoreParameters {
|
|
858
|
+
ignoreParserErrors?: boolean; // Default: false
|
|
859
|
+
ignoreLexerErrors?: boolean; // Default: false
|
|
860
|
+
ignoreValidationErrors?: boolean; // Default: false
|
|
861
|
+
ignoreNonErrorDiagnostics?: boolean; // Default: depends on matcher
|
|
862
|
+
}
|
|
863
|
+
```
|
|
864
|
+
|
|
865
|
+
##### Example: Ignoring Lexer Errors
|
|
866
|
+
|
|
867
|
+
```typescript
|
|
868
|
+
test("document has no errors, ignoring lexer errors", async () => {
|
|
869
|
+
const document = await parse("codeWithLexerErrors");
|
|
870
|
+
expect(document).toHaveNoErrors({ ignoreLexerErrors: true });
|
|
871
|
+
});
|
|
872
|
+
```
|
|
873
|
+
|
|
874
|
+
#### API Reference
|
|
875
|
+
|
|
876
|
+
- Matchers:
|
|
877
|
+
- [toHaveNoErrors](https://borisbrodski.github.io/langium-tools/functions/testing.toHaveNoErrors.html)
|
|
878
|
+
- [toHaveNoIssues](https://borisbrodski.github.io/langium-tools/functions/testing.toHaveNoIssues.html)
|
|
879
|
+
- [toHaveDocumentIssues](https://borisbrodski.github.io/langium-tools/functions/testing.toHaveDocumentIssues.html)
|
|
880
|
+
- [toContainIssue](https://borisbrodski.github.io/langium-tools/functions/testing.toContainIssue.html)
|
|
881
|
+
- Interfaces:
|
|
882
|
+
- [IssueExpectation](https://borisbrodski.github.io/langium-tools/interfaces/testing.IssueExpectation.html)
|
|
883
|
+
- [IgnoreParameters](https://borisbrodski.github.io/langium-tools/interfaces/testing.IgnoreParameters.html)
|
|
884
|
+
- Enums:
|
|
885
|
+
- [DocumentIssueSeverity](https://borisbrodski.github.io/langium-tools/types/base.DocumentIssue.html)
|
|
886
|
+
- [DocumentIssueSource](https://borisbrodski.github.io/langium-tools/enums/base.DocumentIssueSource.html)
|
|
887
|
+
|
|
888
|
+
#### Notes
|
|
889
|
+
|
|
890
|
+
- **Extending Vitest**: The matchers are added to Vitest's expect function by importing `langium-tools/testing`.
|
|
891
|
+
- **Error Messages**: The matchers provide detailed error messages to help you diagnose failing tests.
|
|
892
|
+
|
|
893
|
+
#### Using the `adjusted` Function for Templates
|
|
894
|
+
|
|
895
|
+
In the examples, you might notice the use of a <a href="#adjusted">`adjusted`</a> function to format template strings. This is a utility to clean up multiline strings in tests.
|
|
896
|
+
|
|
897
|
+
See [`adjusted` typedoc](https://borisbrodski.github.io/langium-tools/functions/base.adjusted.html) for more information.
|
|
898
|
+
|
|
899
|
+
#### Conclusion
|
|
900
|
+
|
|
901
|
+
The Vitest matchers provided by `langium-tools` enhance your testing capabilities by allowing you to write expressive and precise assertions for your Langium documents. By utilizing markers and custom matchers, you can create robust tests that ensure your language services work as intended.
|
|
902
|
+
|
|
903
|
+
For more detailed information, refer to the API documentation.
|
|
904
|
+
|
|
905
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
906
|
+
|
|
907
|
+
### Miscellaneous
|
|
908
|
+
|
|
909
|
+
#### `adjusted`
|
|
910
|
+
|
|
911
|
+
The adjusted function is a utility for formatting multi-line template strings, ensuring that indentation and line breaks are preserved correctly. This is particularly useful for generating code snippets or structured text where indentation is essential.
|
|
912
|
+
|
|
913
|
+
See [`adjusted` typedoc](https://borisbrodski.github.io/langium-tools/functions/base.adjusted.html) for more information.
|
|
914
|
+
|
|
915
|
+
##### Features
|
|
916
|
+
|
|
917
|
+
- **Automatic Indentation**: Dynamically inserted placeholders (${...}) are adjusted to match the indentation level of the placeholder itself, making it easy to maintain proper structure in the output.
|
|
918
|
+
- **New lines**: Platform-style newlines, see `adjustedUnix` for Unix-style newlines (`\n`)
|
|
919
|
+
|
|
920
|
+
##### Usage
|
|
921
|
+
|
|
922
|
+
The adjusted function is used as a tagged template literal:
|
|
923
|
+
|
|
924
|
+
```typescript
|
|
925
|
+
import { adjusted } from "langium-tools/base";
|
|
926
|
+
const text = adjusted`
|
|
927
|
+
${cmds}
|
|
928
|
+
if (sayAgain) {
|
|
929
|
+
${cmds}
|
|
930
|
+
}
|
|
931
|
+
`;
|
|
932
|
+
|
|
933
|
+
console.log(text);
|
|
934
|
+
```
|
|
935
|
+
|
|
936
|
+
Output:
|
|
937
|
+
|
|
938
|
+
```
|
|
939
|
+
console.log('Hello,');
|
|
940
|
+
console.log('World!');
|
|
941
|
+
if (sayAgain) {
|
|
942
|
+
console.log('Hello,');
|
|
943
|
+
console.log('World!');
|
|
944
|
+
}
|
|
945
|
+
```
|
|
946
|
+
|
|
947
|
+
Notice, how indentation of the dynamic placeholders is adjusted to match the surrounding code.
|
|
948
|
+
|
|
949
|
+
##### Parameters
|
|
950
|
+
|
|
951
|
+
- **staticParts**: The static (literal) parts of the template string.
|
|
952
|
+
- **substitutions**: The dynamic parts of the template string, which will be injected into the corresponding placeholders in staticParts.
|
|
953
|
+
|
|
954
|
+
##### Return Value
|
|
955
|
+
|
|
956
|
+
The function returns a formatted string with the following properties:
|
|
957
|
+
|
|
958
|
+
- Indentation of dynamic placeholders is adjusted to match the indentation of the placeholder in the template.
|
|
959
|
+
|
|
960
|
+
##### API Reference
|
|
961
|
+
|
|
962
|
+
- [adjusted](https://borisbrodski.github.io/langium-tools/functions/base.adjusted.html)
|
|
963
|
+
|
|
964
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
965
|
+
|
|
966
|
+
### Language - Java
|
|
967
|
+
|
|
968
|
+
#### Generating Java Code with `JavaImportManager` and `generateJavaFile`
|
|
969
|
+
|
|
970
|
+
The `JavaImportManager` and `generateJavaFile` utilities simplify the process of generating well-structured Java code within your Langium-based projects. They handle common boilerplate code such as package declarations and import statements, allowing you to focus on the core content of your Java classes.
|
|
971
|
+
|
|
972
|
+
##### Overview
|
|
973
|
+
|
|
974
|
+
- **JavaImportManager**: Manages Java class imports during code generation, automatically handling import statements and resolving class name collisions.
|
|
975
|
+
- **generateJavaFile**: A utility function that streamlines the creation of Java source files with proper package declarations, imports, and class content.
|
|
976
|
+
|
|
977
|
+
##### Getting Started
|
|
978
|
+
|
|
979
|
+
To use these utilities, you need to:
|
|
980
|
+
|
|
981
|
+
- Import the necessary modules in your code.
|
|
982
|
+
- Define your class content using CompositeGeneratorNode and the provided importManager.
|
|
983
|
+
- Generate the Java file using generateJavaFile.
|
|
984
|
+
|
|
985
|
+
##### Importing the Utilities
|
|
986
|
+
|
|
987
|
+
```typescript
|
|
988
|
+
import { expandToNode } from "langium/generate";
|
|
989
|
+
import { generateJavaFile } from "langium-tools/lang/java";
|
|
990
|
+
import { GeneratorManager } from "langium-tools/generator";
|
|
991
|
+
```
|
|
992
|
+
|
|
993
|
+
##### Using `generateJavaFile`
|
|
994
|
+
|
|
995
|
+
The `generateJavaFile` function generates a Java source file with proper package declaration, imports, and body content. It leverages `JavaImportManager` to manage imports automatically based on the classes used in the body content.
|
|
996
|
+
|
|
997
|
+
##### Function Signature:
|
|
998
|
+
|
|
999
|
+
```typescript
|
|
1000
|
+
generateJavaFile(
|
|
1001
|
+
fileName: string,
|
|
1002
|
+
packageName: string,
|
|
1003
|
+
generatorManager: GeneratorManager,
|
|
1004
|
+
bodyGenerator: (importManager: (fqn: string) => string) => CompositeGeneratorNode,
|
|
1005
|
+
options?: CreateFileOptions
|
|
1006
|
+
): void;
|
|
1007
|
+
```
|
|
1008
|
+
|
|
1009
|
+
- **fileName**: Name of the Java file to be generated (without the `.java` extension).
|
|
1010
|
+
- **packageName**: The package name for the Java file (e.g., `com.example.project`).
|
|
1011
|
+
- **generatorManager**: Manages code generation for a specific model.
|
|
1012
|
+
- **bodyGenerator**: A function that generates the body of the Java file, receiving an importManager function to handle class imports.
|
|
1013
|
+
- **options** _(optional)_: Settings for file creation, such as encoding or overwrite behavior and target directory.
|
|
1014
|
+
|
|
1015
|
+
##### Example: Generating a Simple Java Class
|
|
1016
|
+
|
|
1017
|
+
```typescript
|
|
1018
|
+
generateJavaFile("MyClass", "com.example.project", generatorManager, (imp) => expandToNode`
|
|
1019
|
+
public class MyClass {
|
|
1020
|
+
public ${imp("java.util.Properties")} getProperties() {
|
|
1021
|
+
// ...
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
`),
|
|
1025
|
+
);
|
|
1026
|
+
```
|
|
1027
|
+
|
|
1028
|
+
##### Explanation:
|
|
1029
|
+
|
|
1030
|
+
- **Imports**:
|
|
1031
|
+
- The passed `imp` function is used to import `java.util.Properties`. It returns the appropriate class name (`Properties` in this case), handling imports automatically.
|
|
1032
|
+
|
|
1033
|
+
- **Generated Output**:
|
|
1034
|
+
|
|
1035
|
+
```typescript
|
|
1036
|
+
package com.example.project;
|
|
1037
|
+
|
|
1038
|
+
import java.util.Properties;
|
|
1039
|
+
|
|
1040
|
+
public class MyClass {
|
|
1041
|
+
public Properties getProperties() {
|
|
1042
|
+
// ...
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
```
|
|
1046
|
+
|
|
1047
|
+
##### Managing Imports with JavaImportManager
|
|
1048
|
+
|
|
1049
|
+
The `JavaImportManager` ensures that:
|
|
1050
|
+
|
|
1051
|
+
- Classes from the same package or default packages (like `java.lang`) are not imported unnecessarily.
|
|
1052
|
+
- Class name collisions are resolved by using fully qualified names when needed.
|
|
1053
|
+
- Imports are sorted alphabetically, and duplicates are avoided.
|
|
1054
|
+
|
|
1055
|
+
##### Example: Handling Class Name Collisions
|
|
1056
|
+
|
|
1057
|
+
```typescript
|
|
1058
|
+
private ${imp('com.example.package1.MyClass')} myClass1;
|
|
1059
|
+
private ${imp('com.example.package2.MyClass')} myClass2;
|
|
1060
|
+
);
|
|
1061
|
+
```
|
|
1062
|
+
|
|
1063
|
+
Generated imports:
|
|
1064
|
+
|
|
1065
|
+
```java
|
|
1066
|
+
import com.example.package1.MyClass;
|
|
1067
|
+
```
|
|
1068
|
+
|
|
1069
|
+
Generated output:
|
|
1070
|
+
|
|
1071
|
+
```java
|
|
1072
|
+
private MyClass myClass1;
|
|
1073
|
+
private com.example.package2.MyClass myClass2;
|
|
1074
|
+
```
|
|
1075
|
+
|
|
1076
|
+
##### API Reference
|
|
1077
|
+
|
|
1078
|
+
- Classes:
|
|
1079
|
+
- JavaImportManager
|
|
1080
|
+
- Functions:
|
|
1081
|
+
- generateJavaFile
|
|
1082
|
+
- adjusted
|
|
1083
|
+
- Interfaces:
|
|
1084
|
+
- GeneratorManager
|
|
1085
|
+
- CreateFileOptions
|
|
1086
|
+
|
|
1087
|
+
##### Conclusion
|
|
1088
|
+
|
|
1089
|
+
The `JavaImportManager` and `generateJavaFile` utilities provide powerful tools for generating Java code in a structured and efficient manner. They handle the complexities of import management and file generation, allowing you to focus on implementing the logic of your code generation.
|
|
1090
|
+
|
|
1091
|
+
By integrating these utilities into your Langium projects, you can automate Java code generation with ease and confidence, ensuring that your generated code is clean, consistent, and maintainable.
|
|
1092
|
+
|
|
1093
|
+
For more detailed information, refer to the API documentation linked above.
|
|
1094
|
+
|
|
1095
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
1096
|
+
|
|
1097
|
+
<!-- ROADMAP -->
|
|
1098
|
+
|
|
1099
|
+
## Roadmap
|
|
1100
|
+
|
|
1101
|
+
- [ ] Split packages into `langium-tools` and `langium-test-tools` NPM packages to prevent test helper classes to be released with production code
|
|
1102
|
+
|
|
1103
|
+
See the [open issues](https://github.com/borisbrodski/langium-tools/issues) for a full list of proposed features (and known issues).
|
|
1104
|
+
|
|
1105
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
1106
|
+
|
|
1107
|
+
<!-- CONTRIBUTING -->
|
|
1108
|
+
|
|
1109
|
+
## Contributing
|
|
1110
|
+
|
|
1111
|
+
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
|
|
1112
|
+
|
|
1113
|
+
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
|
|
1114
|
+
Don't forget to give the project a star! Thanks again!
|
|
1115
|
+
|
|
1116
|
+
1. Fork the Project
|
|
1117
|
+
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
|
|
1118
|
+
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
|
|
1119
|
+
|
|
1120
|
+
4. Open a Pull Request
|
|
1121
|
+
|
|
1122
|
+
### Top contributors:
|
|
1123
|
+
|
|
1124
|
+
<a href="https://github.com/borisbrodski/langium-tools/graphs/contributors">
|
|
1125
|
+
<img src="https://contrib.rocks/image?repo=borisbrodski/langium-tools" alt="contrib.rocks image" />
|
|
1126
|
+
</a>
|
|
1127
|
+
|
|
1128
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
1129
|
+
|
|
1130
|
+
<!-- LICENSE -->
|
|
1131
|
+
|
|
1132
|
+
## License
|
|
1133
|
+
|
|
1134
|
+
Distributed under the MIT License. See `LICENSE.txt` for more information.
|
|
1135
|
+
|
|
1136
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
1137
|
+
|
|
1138
|
+
<!-- CONTACT -->
|
|
1139
|
+
|
|
1140
|
+
## Contact
|
|
1141
|
+
|
|
1142
|
+
Boris Brodski - [@BorisBrodski](https://x.com/BorisBrodski) - brodsky_boris@yahoo.com
|
|
1143
|
+
|
|
1144
|
+
Project Link: [https://github.com/borisbrodski/langium-tools](https://github.com/borisbrodski/langium-tools)
|
|
1145
|
+
|
|
1146
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
1147
|
+
|
|
1148
|
+
<!-- ACKNOWLEDGMENTS -->
|
|
1149
|
+
|
|
1150
|
+
## Acknowledgments
|
|
1151
|
+
|
|
1152
|
+
- [Langium](https://langium.org/)
|
|
1153
|
+
|
|
1154
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
1155
|
+
|
|
1156
|
+
<!-- MARKDOWN LINKS & IMAGES -->
|
|
1157
|
+
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
|
|
1158
|
+
|
|
1159
|
+
[contributors-shield]: https://img.shields.io/github/contributors/borisbrodski/langium-tools.svg?style=for-the-badge
|
|
1160
|
+
[contributors-url]: https://github.com/borisbrodski/langium-tools/graphs/contributors
|
|
1161
|
+
[forks-shield]: https://img.shields.io/github/forks/borisbrodski/langium-tools.svg?style=for-the-badge
|
|
1162
|
+
[forks-url]: https://github.com/borisbrodski/langium-tools/network/members
|
|
1163
|
+
[stars-shield]: https://img.shields.io/github/stars/borisbrodski/langium-tools.svg?style=for-the-badge
|
|
1164
|
+
[stars-url]: https://github.com/borisbrodski/langium-tools/stargazers
|
|
1165
|
+
[issues-shield]: https://img.shields.io/github/issues/borisbrodski/langium-tools.svg?style=for-the-badge
|
|
1166
|
+
[issues-url]: https://github.com/borisbrodski/langium-tools/issues
|
|
1167
|
+
[license-shield]: https://img.shields.io/github/license/borisbrodski/langium-tools.svg?style=for-the-badge
|
|
1168
|
+
[license-url]: https://github.com/borisbrodski/langium-tools/blob/master/LICENSE.txt
|
|
1169
|
+
[product-screenshot]: images/screenshot.png
|
|
1170
|
+
[Typescript]: https://shields.io/badge/TypeScript-3178C6?logo=TypeScript&logoColor=FFF&style=flat-square
|
|
1171
|
+
[Typescript-url]: https://www.typescriptlang.org/
|