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.
Files changed (61) hide show
  1. package/README.md +1171 -0
  2. package/dist/base/arrays.d.ts +6 -0
  3. package/dist/base/arrays.js +34 -0
  4. package/dist/base/document-errors.d.ts +56 -0
  5. package/dist/base/document-errors.js +198 -0
  6. package/dist/base/document-issues.d.ts +178 -0
  7. package/dist/base/document-issues.js +306 -0
  8. package/dist/base/index.d.ts +4 -0
  9. package/dist/base/index.js +4 -0
  10. package/dist/base/marker-parser.d.ts +36 -0
  11. package/dist/base/marker-parser.js +51 -0
  12. package/dist/base/string.d.ts +89 -0
  13. package/dist/base/string.js +104 -0
  14. package/dist/generator/generated-content-manager.d.ts +207 -0
  15. package/dist/generator/generated-content-manager.js +242 -0
  16. package/dist/generator/index.d.ts +2 -0
  17. package/dist/generator/index.js +2 -0
  18. package/dist/generator/tools.d.ts +9 -0
  19. package/dist/generator/tools.js +12 -0
  20. package/dist/index.d.ts +4 -0
  21. package/dist/index.js +4 -0
  22. package/dist/lang/index.d.ts +1 -0
  23. package/dist/lang/index.js +1 -0
  24. package/dist/lang/java/common.d.ts +1 -0
  25. package/dist/lang/java/common.js +3 -0
  26. package/dist/lang/java/generator-tools.d.ts +37 -0
  27. package/dist/lang/java/generator-tools.js +48 -0
  28. package/dist/lang/java/import-manager.d.ts +61 -0
  29. package/dist/lang/java/import-manager.js +88 -0
  30. package/dist/lang/java/index.d.ts +3 -0
  31. package/dist/lang/java/index.js +3 -0
  32. package/dist/testing/common.d.ts +1 -0
  33. package/dist/testing/common.js +5 -0
  34. package/dist/testing/generator-testing.d.ts +56 -0
  35. package/dist/testing/generator-testing.js +184 -0
  36. package/dist/testing/index.d.ts +4 -0
  37. package/dist/testing/index.js +4 -0
  38. package/dist/testing/matchers.d.ts +209 -0
  39. package/dist/testing/matchers.js +306 -0
  40. package/dist/testing/parser-tools.d.ts +19 -0
  41. package/dist/testing/parser-tools.js +18 -0
  42. package/package.json +59 -0
  43. package/src/base/arrays.ts +40 -0
  44. package/src/base/document-issues.ts +430 -0
  45. package/src/base/index.ts +4 -0
  46. package/src/base/marker-parser.ts +96 -0
  47. package/src/base/string.ts +117 -0
  48. package/src/generator/generated-content-manager.ts +368 -0
  49. package/src/generator/index.ts +2 -0
  50. package/src/generator/tools.ts +14 -0
  51. package/src/index.ts +5 -0
  52. package/src/lang/index.ts +1 -0
  53. package/src/lang/java/common.ts +4 -0
  54. package/src/lang/java/generator-tools.ts +59 -0
  55. package/src/lang/java/import-manager.ts +98 -0
  56. package/src/lang/java/index.ts +3 -0
  57. package/src/testing/common.ts +5 -0
  58. package/src/testing/generator-testing.ts +266 -0
  59. package/src/testing/index.ts +4 -0
  60. package/src/testing/matchers.ts +503 -0
  61. package/src/testing/parser-tools.ts +34 -0
@@ -0,0 +1,368 @@
1
+ import { AstNode, LangiumDocument, URI } from 'langium';
2
+ import * as fsPromises from 'fs/promises';
3
+ import * as path from 'node:path';
4
+ import { getWorkspaceForDocument } from './tools.js';
5
+
6
+ /**
7
+ * Represents the generated content for files.
8
+ *
9
+ * The map keys are file paths (relative to the output directory), and the values are objects containing:
10
+ * - `content`: The generated content of the file.
11
+ * - `overwrite`: A flag indicating whether to overwrite existing files.
12
+ * - `documentPath`: The path to the source document from which the file was generated.
13
+ */
14
+ export type GeneratedContent = Map<
15
+ string,
16
+ {
17
+ content: string;
18
+ overwrite: boolean;
19
+ documentPath: string;
20
+ }
21
+ >;
22
+
23
+ /**
24
+ * Represents a target output directory for generated files.
25
+ */
26
+ export interface GeneratorTarget {
27
+ /** The name of the target. */
28
+ name: string;
29
+ /** Default value for the `overwrite` flag for the target. */
30
+ overwrite: boolean;
31
+ }
32
+
33
+ /**
34
+ * The default target used when no specific target is provided.
35
+ */
36
+ export const DEFAULT_TARGET: GeneratorTarget = { name: 'DEFAULT', overwrite: true };
37
+
38
+ /**
39
+ * Options for creating a file.
40
+ */
41
+ export interface CreateFileOptions {
42
+ /**
43
+ * If `true`, existing files on the filesystem will be overwritten with the new content.
44
+ * Value `false` can be used for initial generation of files.
45
+ * Defaults to `true` for the default target.
46
+ * Custom targets have their own default value for the `overwrite` flag.
47
+ */
48
+ overwrite?: boolean;
49
+
50
+ /**
51
+ * The output directory target name to use.
52
+ * Defaults to {@link DEFAULT_TARGET}.
53
+ * Different targets can be written to different output directories and can have different default `overwrite` flags.
54
+ */
55
+ target?: string;
56
+ }
57
+
58
+ /**
59
+ * Manages code generation for a specific model.
60
+ *
61
+ * Provides:
62
+ * - Access to the underlying workspace, document, and model.
63
+ * - Methods to collect generated files.
64
+ * - Support for multiple output directories (targets).
65
+ *
66
+ * @typeParam MODEL - The type of the AST node model.
67
+ */
68
+ export interface GeneratorManager<MODEL extends AstNode = AstNode> {
69
+ /**
70
+ * Creates a new file with the specified content and options.
71
+ *
72
+ * @param filePath - The file name with an optional relative path, relative to the output directory.
73
+ * @param content - The generated content of the new file.
74
+ * @param options - Optional settings for file generation.
75
+ */
76
+ createFile(filePath: string, content: string, options?: CreateFileOptions): void;
77
+
78
+ /**
79
+ * Returns the model associated with the current generator.
80
+ *
81
+ * @returns The model of type `MODEL`.
82
+ */
83
+ getModel(): MODEL;
84
+
85
+ /**
86
+ * Returns the associated Langium document, if known.
87
+ *
88
+ * @returns The associated `LangiumDocument`, or `undefined` if not available.
89
+ */
90
+ getDocument(): LangiumDocument<MODEL> | undefined;
91
+
92
+ /**
93
+ * Returns the workspace URI corresponding to the Langium document URI.
94
+ *
95
+ * The URI will be selected from a list of known workspace URIs.
96
+ *
97
+ * @returns The workspace `URI` if it could be determined, or `undefined` otherwise.
98
+ */
99
+ getWorkspaceURI(): URI | undefined;
100
+
101
+ /**
102
+ * Returns the relative path of the Langium document within the determined workspace.
103
+ * See {@link getWorkspaceURI}.
104
+ * If DSL file is outside of all workspace directories, filename with extension (basename) is returned.
105
+ * `/` is used on all platforms as directory separator.
106
+ *
107
+ * @returns The relative path as a string, if the workspace URI could be determined, filename with extension or `undefined` otherwise.
108
+ */
109
+ getDocumentLocalPath(): string | undefined;
110
+ }
111
+
112
+ /**
113
+ * Manages the collection of generated content for code generation.
114
+ *
115
+ * The `GeneratedContentManager` allows you to:
116
+ * - Collect generated files from multiple models.
117
+ * - Handle multiple targets (output directories) with custom overwrite settings.
118
+ * - Write the collected generated content to the filesystem.
119
+ *
120
+ * @example
121
+ * ```typescript
122
+ * const manager = new GeneratedContentManager(optionalListOfWorkspaceURIs);
123
+ *
124
+ * // Generate content for multiple models
125
+ * generator(manager.generatorManagerFor(model1));
126
+ * generator(manager.generatorManagerFor(model2));
127
+ *
128
+ * // Retrieve the collected content (optional)
129
+ * const content = manager.getGeneratedContent();
130
+ *
131
+ * // Write the generated content to disk
132
+ * await manager.writeToDisk('./generated');
133
+ * ```
134
+ *
135
+ * @example
136
+ * ```typescript
137
+ * function generator(manager: GeneratorManager) {
138
+ * const model = manager.getModel();
139
+ * const document = manager.getDocument();
140
+ * const workspaceURI = manager.getWorkspaceURI();
141
+ * const localPath = manager.getDocumentLocalPath();
142
+ *
143
+ * // Generate files
144
+ * manager.createFile('src-gen/abstract_process.ts', '// Generated by Langium. Do not edit.');
145
+ * manager.createFile('src/process.ts', '// Initially generated by Langium', { overwrite: false });
146
+ * }
147
+ * ```
148
+ *
149
+ * @see {@link GeneratorManager}
150
+ * @category Generator
151
+ */
152
+ export class GeneratedContentManager {
153
+ private readonly generatedContentMap: Map<string, GeneratedContent> = new Map([
154
+ [DEFAULT_TARGET.name, new Map()],
155
+ ]);
156
+ private readonly targetMap: Map<string, GeneratorTarget> = new Map();
157
+ private readonly workspaceURIs?: URI[];
158
+
159
+ /**
160
+ * Creates a new instance of `GeneratedContentManager`.
161
+ *
162
+ * @param workspaceDirs - Optional list of workspace directories (as strings or URIs).
163
+ * Used to determine the workspace URI for documents.
164
+ */
165
+ constructor(workspaceDirs?: Array<string | URI>) {
166
+ this.workspaceURIs = workspaceDirs?.map((dir) => (typeof dir === 'string' ? URI.parse(dir) : dir));
167
+ this.targetMap.set(DEFAULT_TARGET.name, DEFAULT_TARGET);
168
+ }
169
+
170
+ /**
171
+ * Adds a new target to the generator output.
172
+ * The target name must be unique.
173
+ *
174
+ * @param target - The target to add with name and other settings.
175
+ *
176
+ * @throws {Error} If the target has already been added.
177
+ */
178
+ addTarget(target: GeneratorTarget): void {
179
+ if (this.generatedContentMap.has(target.name)) {
180
+ throw new Error(`Target "${target.name}" has already been added`);
181
+ }
182
+ this.generatedContentMap.set(target.name, new Map());
183
+ this.targetMap.set(target.name, target);
184
+ }
185
+
186
+ /**
187
+ * Creates a new `GeneratorManager` for the given AST model.
188
+ *
189
+ * @typeParam MODEL - The type of the AST node model.
190
+ * @param model - The AST model for which to create the generator manager.
191
+ *
192
+ * @returns A new instance of `GeneratorManager` associated with the provided model.
193
+ */
194
+ generatorManagerFor<MODEL extends AstNode = AstNode>(model: MODEL): GeneratorManager<MODEL> {
195
+ const documentURI = model.$document?.uri;
196
+ const documentURIString = documentURI?.toString();
197
+ const workspaceURI = getWorkspaceForDocument(documentURI, this.workspaceURIs);
198
+ const workspaceRelativePath = workspaceURI !== undefined && documentURI !== undefined
199
+ ? path.posix.relative(workspaceURI.path, documentURI.path)
200
+ : undefined;
201
+ const relativePath =
202
+ workspaceRelativePath ||
203
+ (documentURIString !== undefined
204
+ ? path.basename(documentURIString)
205
+ : undefined);
206
+ const documentPath = workspaceRelativePath || documentURI?.toString() || 'document URI undefined';
207
+ return {
208
+ createFile: (filePath: string, content: string, options?: CreateFileOptions) => {
209
+ const target = this.#getTarget(options?.target);
210
+ const overwrite = options?.overwrite ?? target.overwrite;
211
+ this.createFile(target.name, filePath, content, overwrite, documentPath);
212
+ },
213
+ getModel: () => model,
214
+ getDocument: () => model.$document as LangiumDocument<MODEL> | undefined,
215
+ getWorkspaceURI: () => workspaceURI,
216
+ getDocumentLocalPath: () => relativePath,
217
+ };
218
+ }
219
+
220
+ /**
221
+ * Creates a new file with the given content and metadata.
222
+ *
223
+ * @param targetName - The target name for which the file is generated. Defaults to the default target.
224
+ * @param filePath - The relative path of the file to create.
225
+ * @param content - The content of the file.
226
+ * @param overwrite - Whether to overwrite the file if it already exists.
227
+ * @param documentPath - The path to the source document from which the file was generated.
228
+ *
229
+ * @throws {Error} If a file with the same path and different content or overwrite flag has already been generated.
230
+ */
231
+ createFile(
232
+ targetName: string | undefined,
233
+ filePath: string,
234
+ content: string,
235
+ overwrite: boolean,
236
+ documentPath: string
237
+ ): void {
238
+ const target = this.#getTarget(targetName);
239
+ const generatedContent = this.getGeneratedContent(target.name);
240
+ const existingContent = generatedContent?.get(filePath);
241
+ if (existingContent) {
242
+ if (existingContent.content !== content) {
243
+ throw new Error(
244
+ `Conflict generating file "${filePath}" from "${documentPath}": A file with different content was already generated from "${existingContent.documentPath}".`
245
+ );
246
+ }
247
+ if (existingContent.overwrite !== overwrite) {
248
+ throw new Error(
249
+ `Conflict generating file "${filePath}" from "${documentPath}": A file with different overwrite flag was already generated from "${existingContent.documentPath}".`
250
+ );
251
+ }
252
+ // Allow generating the same file multiple times with the same content and overwrite flag
253
+ } else {
254
+ generatedContent.set(filePath, {
255
+ content,
256
+ overwrite: overwrite,
257
+ documentPath: documentPath,
258
+ });
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Return all known targets.
264
+ * @returns An array of all known targets.
265
+ */
266
+ getTargets(): GeneratorTarget[] {
267
+ return Array.from(this.targetMap.values());
268
+ }
269
+
270
+ /**
271
+ * Returns the generated content for the provided target or the default target.
272
+ *
273
+ * @param targetName - The target name for which to get the generated content.
274
+ * If not provided, the default target is used.
275
+ *
276
+ * @returns A `GeneratedContent` map containing the generated files.
277
+ *
278
+ * @throws {Error} If the specified target is not registered.
279
+ */
280
+ getGeneratedContent(targetName?: string): GeneratedContent {
281
+ return this.generatedContentMap.get(this.#getTarget(targetName).name)!;
282
+ }
283
+
284
+ /**
285
+ * Returns the Target object for the provided target name or the default target.
286
+ *
287
+ * @param targetName - The target name for which to get the generated content.
288
+ * If not provided, the default target is used.
289
+ *
290
+ * @returns The `GeneratorTarget` object for the specified target.
291
+ *
292
+ * @throws {Error} If the specified target is not registered.
293
+ */
294
+ #getTarget(targetName?: string): GeneratorTarget {
295
+ const resolvedTargetName = (targetName || DEFAULT_TARGET.name);
296
+ if (!this.generatedContentMap.has(resolvedTargetName)) {
297
+ throw new Error(`Target "${resolvedTargetName}" is not registered`);
298
+ }
299
+ return this.targetMap.get(resolvedTargetName)!;
300
+ }
301
+
302
+ /**
303
+ * Writes the generated content for a target to the file system asynchronously.
304
+ *
305
+ * Existing files are only overwritten if the overwrite flag is set (default behavior).
306
+ * If the file already exists and the content is the same, the file is not overwritten,
307
+ * preserving the timestamp and not triggering file system file change events.
308
+ *
309
+ * @param outputDir - The output directory where the files will be written.
310
+ * @param target - The target name whose content should be written.
311
+ * If not provided, the default target is used.
312
+ *
313
+ * @throws {Error} If an error occurs during file or directory operations.
314
+ */
315
+ async writeToDisk(outputDir: string, target?: string): Promise<void> {
316
+ const generatedContent = this.getGeneratedContent(target);
317
+
318
+ // Ensure the output directory exists
319
+ try {
320
+ await fsPromises.mkdir(outputDir, { recursive: true });
321
+ } catch (error) {
322
+ console.error(`Error creating directory "${outputDir}": ${(error as Error).message}`);
323
+ throw error;
324
+ }
325
+
326
+ for (const [file, content] of generatedContent) {
327
+ const absoluteFilePath = path.join(outputDir, file);
328
+ const fileDir = path.dirname(absoluteFilePath);
329
+
330
+ // Ensure the directory for the file exists
331
+ try {
332
+ await fsPromises.mkdir(fileDir, { recursive: true });
333
+ } catch (error) {
334
+ console.error(`Error creating directory "${fileDir}": ${(error as Error).message}`);
335
+ throw error;
336
+ }
337
+
338
+ let fileExists = false;
339
+ let existingContent = '';
340
+
341
+ // Check if the file exists and read its content
342
+ try {
343
+ existingContent = await fsPromises.readFile(absoluteFilePath, 'utf8');
344
+ fileExists = true;
345
+ } catch (error) {
346
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
347
+ console.error(`Error reading file "${absoluteFilePath}": ${(error as Error).message}`);
348
+ throw error;
349
+ }
350
+ // File does not exist, proceed to write
351
+ }
352
+
353
+ // Determine whether to write the file
354
+ if (fileExists && (!content.overwrite || existingContent === content.content)) {
355
+ // Skip writing the file if overwrite is false or content is the same
356
+ continue;
357
+ }
358
+
359
+ // Write the file
360
+ try {
361
+ await fsPromises.writeFile(absoluteFilePath, content.content);
362
+ } catch (error) {
363
+ console.error(`Error writing file "${absoluteFilePath}": ${(error as Error).message}`);
364
+ throw error;
365
+ }
366
+ }
367
+ }
368
+ }
@@ -0,0 +1,2 @@
1
+ export * from './generated-content-manager.js';
2
+ export * from './tools.js';
@@ -0,0 +1,14 @@
1
+ import { URI } from "langium";
2
+
3
+ /**
4
+ * Return workspace folder {URI} (if found) matching the document URI.
5
+ *
6
+ * @param {URI} [documentURI] document URI
7
+ * @param {URI[]} [workspaceURIs] a list of workspace URIs to consider. Optional
8
+ * @returns {URI} one of the URIs from <code>workspaceURIs</code> or <code>undefined</code>, if the document couldn't be matched to any workspaces.
9
+ */
10
+ export function getWorkspaceForDocument(documentURI?: URI, workspaceURIs?: URI[]): URI | undefined {
11
+ return workspaceURIs?.find(workspaceURI => {
12
+ return documentURI?.toString().startsWith(workspaceURI.toString());
13
+ });
14
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * as base from './base/index.js';
2
+ export * as generator from './generator/index.js';
3
+ export * as testing from './testing/index.js';
4
+ export * as lang from './lang/index.js';
5
+
@@ -0,0 +1 @@
1
+ export * as java from './java/index.js';
@@ -0,0 +1,4 @@
1
+ export function packageToPath(packageName?: string): string | unknown {
2
+ return packageName?.replace(/\./g, "/");
3
+ }
4
+
@@ -0,0 +1,59 @@
1
+ import { CreateFileOptions, GeneratorManager } from "langium-tools/generator";
2
+ import { CompositeGeneratorNode, expandToNode, toString } from "langium/generate";
3
+ import { packageToPath } from "./common.js";
4
+ import { JavaImportManager } from "./import-manager.js";
5
+
6
+ /**
7
+ * Generates a Java source file with proper package declaration, imports, and body content.
8
+ *
9
+ * This function simplifies the generation of Java files by handling common boilerplate code such as
10
+ * package declarations and import statements. It leverages a `JavaImportManager` to manage imports
11
+ * automatically based on the classes used in the body content.
12
+ *
13
+ * @param {string} fileName - The name of the Java file to be generated (without the `.java` extension).
14
+ * @param {string} packageName - The package name for the Java file (e.g., `com.example.project`).
15
+ * @param {GeneratorManager} generatorManager - The manager responsible for handling file creation and output.
16
+ * @param {(importManager: (fqn: string) => string) => CompositeGeneratorNode} bodyGenerator - A function that generates
17
+ * the body of the Java file. It receives an `importManager` function to handle class imports and returns a `CompositeGeneratorNode`
18
+ * representing the body content.
19
+ * @param {CreateFileOptions} [options] - Optional settings for file creation, such as encoding or overwrite behavior.
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * generateJavaFile(
24
+ * 'MyClass',
25
+ * 'com.example.project',
26
+ * generatorManager,
27
+ * (importClass) => expandToNode`
28
+ * public class MyClass {
29
+ * public ${imp('java.util.Properties')} getProperties() {
30
+ * // ...
31
+ * }
32
+ * }
33
+ * }`
34
+ * );
35
+ * ```
36
+ *
37
+ * The above example generates a Java class `MyClass` in the package `com.example.project`, with an imported `java.util.Properties`.
38
+ * The `imp` function handles the import management, ensuring that `java.util.Properties` is imported and conflicts are resolved.
39
+ */
40
+ export function generateJavaFile(
41
+ fileName: string,
42
+ packageName: string,
43
+ generatorManager: GeneratorManager,
44
+ bodyGenerator: (importManager: (fqn: string) => string) => CompositeGeneratorNode,
45
+ options?: CreateFileOptions
46
+ ) {
47
+ const importManager = new JavaImportManager(packageName);
48
+
49
+ const body = bodyGenerator(fqn => importManager.useClass(fqn));
50
+
51
+ generatorManager.createFile(`${packageToPath(packageName)}/${fileName}.java`, toString(expandToNode`
52
+ package ${packageName};
53
+
54
+ ${importManager.generateImports()}
55
+
56
+ ${body}
57
+ `), options);
58
+ }
59
+
@@ -0,0 +1,98 @@
1
+ import { EOL } from "node:os";
2
+
3
+ // TODO: Add support for java.lang without import
4
+
5
+ /**
6
+ * A utility class for managing Java imports during code generation.
7
+ *
8
+ * This class simplifies the handling of Java imports by allowing you to register
9
+ * full qualified class names and ensuring that simple class names do not collide.
10
+ *
11
+ * ## Example
12
+ * ```typescript
13
+ * const importManager = new JavaImportManager();
14
+ *
15
+ * const code = `
16
+ * ${importManager.useClass('java.util.List');} list1;
17
+ * ${importManager.useClass('java.awt.List');} list2;
18
+ * `
19
+ * console.log(code);
20
+ * // Output:
21
+ * // List list1;
22
+ * // java.awt.List list2;
23
+ *
24
+ * console.log(importManager.generateImports());
25
+ * // Output:
26
+ * // import java.awt.List;
27
+ * ```
28
+ * Note, that the import manager will only generate imports for classes that are actually used.
29
+ * Conflicting class names will be resolved by using the full qualified name.
30
+ */
31
+ export class JavaImportManager {
32
+ readonly classes: Map<string, string> = new Map();
33
+ readonly currentPackage: string;
34
+
35
+ /**
36
+ * Creates a new Java import manager.
37
+ *
38
+ * @param {string} currentPackage - The current package to use. Classes from this package shouldn't be imported.
39
+ */
40
+ constructor(currentPackage: string = "") {
41
+ this.currentPackage = currentPackage;
42
+ }
43
+
44
+
45
+ /**
46
+ * Registers a class for use in the generated Java code and returns a suitable name.
47
+ *
48
+ * If the simple name of the provided full qualified name is not already registered, this method
49
+ * registers it and returns the simple name. If a collision occurs (i.e., two different full
50
+ * qualified names share the same simple name), the method returns the full qualified name instead.
51
+ *
52
+ * This method should be called with the same full qualified name every time it is used in the generated code.
53
+ *
54
+ * @param {string} fullQualifiedName - The fully qualified name of the class (e.g., `java.util.List`).
55
+ * @returns {string} The name to use in the generated code, either the simple class name or the full qualified name.
56
+ */
57
+ useClass(fullQualifiedName: string): string {
58
+ const dotIndex = fullQualifiedName.lastIndexOf(".");
59
+ if (dotIndex === -1) {
60
+ return fullQualifiedName;
61
+ }
62
+
63
+ const name = fullQualifiedName.slice(dotIndex + 1);
64
+
65
+ const packageName = fullQualifiedName.slice(0, dotIndex);
66
+ if (packageName === this.currentPackage) {
67
+ if (!this.classes.has(name)) {
68
+ this.classes.set(name, "");
69
+ return name;
70
+ } else if (this.classes.get(name) === "") {
71
+ return name;
72
+ }
73
+ }
74
+
75
+ if (!this.classes.has(name)) {
76
+ this.classes.set(name, fullQualifiedName);
77
+ return name;
78
+ }
79
+ const importedFQN = this.classes.get(name);
80
+ return (importedFQN === fullQualifiedName) ? name : fullQualifiedName;
81
+ }
82
+
83
+ /**
84
+ * Generates a list of Java import statements based on the registered classes.
85
+ *
86
+ * This method iterates over the registered classes and produces the corresponding
87
+ * import statements in alphabetical order. The result can be directly included at
88
+ * the beginning of a Java file.
89
+ *
90
+ * Method {@link useClass} shouldn't be called after this method.
91
+ *
92
+ * @returns {string} A formatted string containing all the import statements, separated by line breaks.
93
+ */
94
+ generateImports(): string {
95
+ return Array.from(this.classes.values()).filter(fqn => fqn.length > 0).map(fqn => `import ${fqn};`).sort().join(EOL);
96
+ }
97
+ }
98
+
@@ -0,0 +1,3 @@
1
+ export * from './common.js';
2
+ export * from './generator-tools.js';
3
+ export * from './import-manager.js';
@@ -0,0 +1,5 @@
1
+ export function using<T>(obj: T, block: (it: T) => void): T {
2
+ block(obj);
3
+ return obj;
4
+ };
5
+