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,207 @@
1
+ import { AstNode, LangiumDocument, URI } from 'langium';
2
+ /**
3
+ * Represents the generated content for files.
4
+ *
5
+ * The map keys are file paths (relative to the output directory), and the values are objects containing:
6
+ * - `content`: The generated content of the file.
7
+ * - `overwrite`: A flag indicating whether to overwrite existing files.
8
+ * - `documentPath`: The path to the source document from which the file was generated.
9
+ */
10
+ export type GeneratedContent = Map<string, {
11
+ content: string;
12
+ overwrite: boolean;
13
+ documentPath: string;
14
+ }>;
15
+ /**
16
+ * Represents a target output directory for generated files.
17
+ */
18
+ export interface GeneratorTarget {
19
+ /** The name of the target. */
20
+ name: string;
21
+ /** Default value for the `overwrite` flag for the target. */
22
+ overwrite: boolean;
23
+ }
24
+ /**
25
+ * The default target used when no specific target is provided.
26
+ */
27
+ export declare const DEFAULT_TARGET: GeneratorTarget;
28
+ /**
29
+ * Options for creating a file.
30
+ */
31
+ export interface CreateFileOptions {
32
+ /**
33
+ * If `true`, existing files on the filesystem will be overwritten with the new content.
34
+ * Value `false` can be used for initial generation of files.
35
+ * Defaults to `true` for the default target.
36
+ * Custom targets have their own default value for the `overwrite` flag.
37
+ */
38
+ overwrite?: boolean;
39
+ /**
40
+ * The output directory target name to use.
41
+ * Defaults to {@link DEFAULT_TARGET}.
42
+ * Different targets can be written to different output directories and can have different default `overwrite` flags.
43
+ */
44
+ target?: string;
45
+ }
46
+ /**
47
+ * Manages code generation for a specific model.
48
+ *
49
+ * Provides:
50
+ * - Access to the underlying workspace, document, and model.
51
+ * - Methods to collect generated files.
52
+ * - Support for multiple output directories (targets).
53
+ *
54
+ * @typeParam MODEL - The type of the AST node model.
55
+ */
56
+ export interface GeneratorManager<MODEL extends AstNode = AstNode> {
57
+ /**
58
+ * Creates a new file with the specified content and options.
59
+ *
60
+ * @param filePath - The file name with an optional relative path, relative to the output directory.
61
+ * @param content - The generated content of the new file.
62
+ * @param options - Optional settings for file generation.
63
+ */
64
+ createFile(filePath: string, content: string, options?: CreateFileOptions): void;
65
+ /**
66
+ * Returns the model associated with the current generator.
67
+ *
68
+ * @returns The model of type `MODEL`.
69
+ */
70
+ getModel(): MODEL;
71
+ /**
72
+ * Returns the associated Langium document, if known.
73
+ *
74
+ * @returns The associated `LangiumDocument`, or `undefined` if not available.
75
+ */
76
+ getDocument(): LangiumDocument<MODEL> | undefined;
77
+ /**
78
+ * Returns the workspace URI corresponding to the Langium document URI.
79
+ *
80
+ * The URI will be selected from a list of known workspace URIs.
81
+ *
82
+ * @returns The workspace `URI` if it could be determined, or `undefined` otherwise.
83
+ */
84
+ getWorkspaceURI(): URI | undefined;
85
+ /**
86
+ * Returns the relative path of the Langium document within the determined workspace.
87
+ * See {@link getWorkspaceURI}.
88
+ * If DSL file is outside of all workspace directories, filename with extension (basename) is returned.
89
+ * `/` is used on all platforms as directory separator.
90
+ *
91
+ * @returns The relative path as a string, if the workspace URI could be determined, filename with extension or `undefined` otherwise.
92
+ */
93
+ getDocumentLocalPath(): string | undefined;
94
+ }
95
+ /**
96
+ * Manages the collection of generated content for code generation.
97
+ *
98
+ * The `GeneratedContentManager` allows you to:
99
+ * - Collect generated files from multiple models.
100
+ * - Handle multiple targets (output directories) with custom overwrite settings.
101
+ * - Write the collected generated content to the filesystem.
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * const manager = new GeneratedContentManager(optionalListOfWorkspaceURIs);
106
+ *
107
+ * // Generate content for multiple models
108
+ * generator(manager.generatorManagerFor(model1));
109
+ * generator(manager.generatorManagerFor(model2));
110
+ *
111
+ * // Retrieve the collected content (optional)
112
+ * const content = manager.getGeneratedContent();
113
+ *
114
+ * // Write the generated content to disk
115
+ * await manager.writeToDisk('./generated');
116
+ * ```
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * function generator(manager: GeneratorManager) {
121
+ * const model = manager.getModel();
122
+ * const document = manager.getDocument();
123
+ * const workspaceURI = manager.getWorkspaceURI();
124
+ * const localPath = manager.getDocumentLocalPath();
125
+ *
126
+ * // Generate files
127
+ * manager.createFile('src-gen/abstract_process.ts', '// Generated by Langium. Do not edit.');
128
+ * manager.createFile('src/process.ts', '// Initially generated by Langium', { overwrite: false });
129
+ * }
130
+ * ```
131
+ *
132
+ * @see {@link GeneratorManager}
133
+ * @category Generator
134
+ */
135
+ export declare class GeneratedContentManager {
136
+ #private;
137
+ private readonly generatedContentMap;
138
+ private readonly targetMap;
139
+ private readonly workspaceURIs?;
140
+ /**
141
+ * Creates a new instance of `GeneratedContentManager`.
142
+ *
143
+ * @param workspaceDirs - Optional list of workspace directories (as strings or URIs).
144
+ * Used to determine the workspace URI for documents.
145
+ */
146
+ constructor(workspaceDirs?: Array<string | URI>);
147
+ /**
148
+ * Adds a new target to the generator output.
149
+ * The target name must be unique.
150
+ *
151
+ * @param target - The target to add with name and other settings.
152
+ *
153
+ * @throws {Error} If the target has already been added.
154
+ */
155
+ addTarget(target: GeneratorTarget): void;
156
+ /**
157
+ * Creates a new `GeneratorManager` for the given AST model.
158
+ *
159
+ * @typeParam MODEL - The type of the AST node model.
160
+ * @param model - The AST model for which to create the generator manager.
161
+ *
162
+ * @returns A new instance of `GeneratorManager` associated with the provided model.
163
+ */
164
+ generatorManagerFor<MODEL extends AstNode = AstNode>(model: MODEL): GeneratorManager<MODEL>;
165
+ /**
166
+ * Creates a new file with the given content and metadata.
167
+ *
168
+ * @param targetName - The target name for which the file is generated. Defaults to the default target.
169
+ * @param filePath - The relative path of the file to create.
170
+ * @param content - The content of the file.
171
+ * @param overwrite - Whether to overwrite the file if it already exists.
172
+ * @param documentPath - The path to the source document from which the file was generated.
173
+ *
174
+ * @throws {Error} If a file with the same path and different content or overwrite flag has already been generated.
175
+ */
176
+ createFile(targetName: string | undefined, filePath: string, content: string, overwrite: boolean, documentPath: string): void;
177
+ /**
178
+ * Return all known targets.
179
+ * @returns An array of all known targets.
180
+ */
181
+ getTargets(): GeneratorTarget[];
182
+ /**
183
+ * Returns the generated content for the provided target or the default target.
184
+ *
185
+ * @param targetName - The target name for which to get the generated content.
186
+ * If not provided, the default target is used.
187
+ *
188
+ * @returns A `GeneratedContent` map containing the generated files.
189
+ *
190
+ * @throws {Error} If the specified target is not registered.
191
+ */
192
+ getGeneratedContent(targetName?: string): GeneratedContent;
193
+ /**
194
+ * Writes the generated content for a target to the file system asynchronously.
195
+ *
196
+ * Existing files are only overwritten if the overwrite flag is set (default behavior).
197
+ * If the file already exists and the content is the same, the file is not overwritten,
198
+ * preserving the timestamp and not triggering file system file change events.
199
+ *
200
+ * @param outputDir - The output directory where the files will be written.
201
+ * @param target - The target name whose content should be written.
202
+ * If not provided, the default target is used.
203
+ *
204
+ * @throws {Error} If an error occurs during file or directory operations.
205
+ */
206
+ writeToDisk(outputDir: string, target?: string): Promise<void>;
207
+ }
@@ -0,0 +1,242 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
6
+ var _GeneratedContentManager_instances, _GeneratedContentManager_getTarget;
7
+ import { URI } from 'langium';
8
+ import * as fsPromises from 'fs/promises';
9
+ import * as path from 'node:path';
10
+ import { getWorkspaceForDocument } from './tools.js';
11
+ /**
12
+ * The default target used when no specific target is provided.
13
+ */
14
+ export const DEFAULT_TARGET = { name: 'DEFAULT', overwrite: true };
15
+ /**
16
+ * Manages the collection of generated content for code generation.
17
+ *
18
+ * The `GeneratedContentManager` allows you to:
19
+ * - Collect generated files from multiple models.
20
+ * - Handle multiple targets (output directories) with custom overwrite settings.
21
+ * - Write the collected generated content to the filesystem.
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * const manager = new GeneratedContentManager(optionalListOfWorkspaceURIs);
26
+ *
27
+ * // Generate content for multiple models
28
+ * generator(manager.generatorManagerFor(model1));
29
+ * generator(manager.generatorManagerFor(model2));
30
+ *
31
+ * // Retrieve the collected content (optional)
32
+ * const content = manager.getGeneratedContent();
33
+ *
34
+ * // Write the generated content to disk
35
+ * await manager.writeToDisk('./generated');
36
+ * ```
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * function generator(manager: GeneratorManager) {
41
+ * const model = manager.getModel();
42
+ * const document = manager.getDocument();
43
+ * const workspaceURI = manager.getWorkspaceURI();
44
+ * const localPath = manager.getDocumentLocalPath();
45
+ *
46
+ * // Generate files
47
+ * manager.createFile('src-gen/abstract_process.ts', '// Generated by Langium. Do not edit.');
48
+ * manager.createFile('src/process.ts', '// Initially generated by Langium', { overwrite: false });
49
+ * }
50
+ * ```
51
+ *
52
+ * @see {@link GeneratorManager}
53
+ * @category Generator
54
+ */
55
+ export class GeneratedContentManager {
56
+ /**
57
+ * Creates a new instance of `GeneratedContentManager`.
58
+ *
59
+ * @param workspaceDirs - Optional list of workspace directories (as strings or URIs).
60
+ * Used to determine the workspace URI for documents.
61
+ */
62
+ constructor(workspaceDirs) {
63
+ _GeneratedContentManager_instances.add(this);
64
+ this.generatedContentMap = new Map([
65
+ [DEFAULT_TARGET.name, new Map()],
66
+ ]);
67
+ this.targetMap = new Map();
68
+ this.workspaceURIs = workspaceDirs === null || workspaceDirs === void 0 ? void 0 : workspaceDirs.map((dir) => (typeof dir === 'string' ? URI.parse(dir) : dir));
69
+ this.targetMap.set(DEFAULT_TARGET.name, DEFAULT_TARGET);
70
+ }
71
+ /**
72
+ * Adds a new target to the generator output.
73
+ * The target name must be unique.
74
+ *
75
+ * @param target - The target to add with name and other settings.
76
+ *
77
+ * @throws {Error} If the target has already been added.
78
+ */
79
+ addTarget(target) {
80
+ if (this.generatedContentMap.has(target.name)) {
81
+ throw new Error(`Target "${target.name}" has already been added`);
82
+ }
83
+ this.generatedContentMap.set(target.name, new Map());
84
+ this.targetMap.set(target.name, target);
85
+ }
86
+ /**
87
+ * Creates a new `GeneratorManager` for the given AST model.
88
+ *
89
+ * @typeParam MODEL - The type of the AST node model.
90
+ * @param model - The AST model for which to create the generator manager.
91
+ *
92
+ * @returns A new instance of `GeneratorManager` associated with the provided model.
93
+ */
94
+ generatorManagerFor(model) {
95
+ var _a;
96
+ const documentURI = (_a = model.$document) === null || _a === void 0 ? void 0 : _a.uri;
97
+ const documentURIString = documentURI === null || documentURI === void 0 ? void 0 : documentURI.toString();
98
+ const workspaceURI = getWorkspaceForDocument(documentURI, this.workspaceURIs);
99
+ const workspaceRelativePath = workspaceURI !== undefined && documentURI !== undefined
100
+ ? path.posix.relative(workspaceURI.path, documentURI.path)
101
+ : undefined;
102
+ const relativePath = workspaceRelativePath ||
103
+ (documentURIString !== undefined
104
+ ? path.basename(documentURIString)
105
+ : undefined);
106
+ const documentPath = workspaceRelativePath || (documentURI === null || documentURI === void 0 ? void 0 : documentURI.toString()) || 'document URI undefined';
107
+ return {
108
+ createFile: (filePath, content, options) => {
109
+ var _a;
110
+ const target = __classPrivateFieldGet(this, _GeneratedContentManager_instances, "m", _GeneratedContentManager_getTarget).call(this, options === null || options === void 0 ? void 0 : options.target);
111
+ const overwrite = (_a = options === null || options === void 0 ? void 0 : options.overwrite) !== null && _a !== void 0 ? _a : target.overwrite;
112
+ this.createFile(target.name, filePath, content, overwrite, documentPath);
113
+ },
114
+ getModel: () => model,
115
+ getDocument: () => model.$document,
116
+ getWorkspaceURI: () => workspaceURI,
117
+ getDocumentLocalPath: () => relativePath,
118
+ };
119
+ }
120
+ /**
121
+ * Creates a new file with the given content and metadata.
122
+ *
123
+ * @param targetName - The target name for which the file is generated. Defaults to the default target.
124
+ * @param filePath - The relative path of the file to create.
125
+ * @param content - The content of the file.
126
+ * @param overwrite - Whether to overwrite the file if it already exists.
127
+ * @param documentPath - The path to the source document from which the file was generated.
128
+ *
129
+ * @throws {Error} If a file with the same path and different content or overwrite flag has already been generated.
130
+ */
131
+ createFile(targetName, filePath, content, overwrite, documentPath) {
132
+ const target = __classPrivateFieldGet(this, _GeneratedContentManager_instances, "m", _GeneratedContentManager_getTarget).call(this, targetName);
133
+ const generatedContent = this.getGeneratedContent(target.name);
134
+ const existingContent = generatedContent === null || generatedContent === void 0 ? void 0 : generatedContent.get(filePath);
135
+ if (existingContent) {
136
+ if (existingContent.content !== content) {
137
+ throw new Error(`Conflict generating file "${filePath}" from "${documentPath}": A file with different content was already generated from "${existingContent.documentPath}".`);
138
+ }
139
+ if (existingContent.overwrite !== overwrite) {
140
+ throw new Error(`Conflict generating file "${filePath}" from "${documentPath}": A file with different overwrite flag was already generated from "${existingContent.documentPath}".`);
141
+ }
142
+ // Allow generating the same file multiple times with the same content and overwrite flag
143
+ }
144
+ else {
145
+ generatedContent.set(filePath, {
146
+ content,
147
+ overwrite: overwrite,
148
+ documentPath: documentPath,
149
+ });
150
+ }
151
+ }
152
+ /**
153
+ * Return all known targets.
154
+ * @returns An array of all known targets.
155
+ */
156
+ getTargets() {
157
+ return Array.from(this.targetMap.values());
158
+ }
159
+ /**
160
+ * Returns the generated content for the provided target or the default target.
161
+ *
162
+ * @param targetName - The target name for which to get the generated content.
163
+ * If not provided, the default target is used.
164
+ *
165
+ * @returns A `GeneratedContent` map containing the generated files.
166
+ *
167
+ * @throws {Error} If the specified target is not registered.
168
+ */
169
+ getGeneratedContent(targetName) {
170
+ return this.generatedContentMap.get(__classPrivateFieldGet(this, _GeneratedContentManager_instances, "m", _GeneratedContentManager_getTarget).call(this, targetName).name);
171
+ }
172
+ /**
173
+ * Writes the generated content for a target to the file system asynchronously.
174
+ *
175
+ * Existing files are only overwritten if the overwrite flag is set (default behavior).
176
+ * If the file already exists and the content is the same, the file is not overwritten,
177
+ * preserving the timestamp and not triggering file system file change events.
178
+ *
179
+ * @param outputDir - The output directory where the files will be written.
180
+ * @param target - The target name whose content should be written.
181
+ * If not provided, the default target is used.
182
+ *
183
+ * @throws {Error} If an error occurs during file or directory operations.
184
+ */
185
+ async writeToDisk(outputDir, target) {
186
+ const generatedContent = this.getGeneratedContent(target);
187
+ // Ensure the output directory exists
188
+ try {
189
+ await fsPromises.mkdir(outputDir, { recursive: true });
190
+ }
191
+ catch (error) {
192
+ console.error(`Error creating directory "${outputDir}": ${error.message}`);
193
+ throw error;
194
+ }
195
+ for (const [file, content] of generatedContent) {
196
+ const absoluteFilePath = path.join(outputDir, file);
197
+ const fileDir = path.dirname(absoluteFilePath);
198
+ // Ensure the directory for the file exists
199
+ try {
200
+ await fsPromises.mkdir(fileDir, { recursive: true });
201
+ }
202
+ catch (error) {
203
+ console.error(`Error creating directory "${fileDir}": ${error.message}`);
204
+ throw error;
205
+ }
206
+ let fileExists = false;
207
+ let existingContent = '';
208
+ // Check if the file exists and read its content
209
+ try {
210
+ existingContent = await fsPromises.readFile(absoluteFilePath, 'utf8');
211
+ fileExists = true;
212
+ }
213
+ catch (error) {
214
+ if (error.code !== 'ENOENT') {
215
+ console.error(`Error reading file "${absoluteFilePath}": ${error.message}`);
216
+ throw error;
217
+ }
218
+ // File does not exist, proceed to write
219
+ }
220
+ // Determine whether to write the file
221
+ if (fileExists && (!content.overwrite || existingContent === content.content)) {
222
+ // Skip writing the file if overwrite is false or content is the same
223
+ continue;
224
+ }
225
+ // Write the file
226
+ try {
227
+ await fsPromises.writeFile(absoluteFilePath, content.content);
228
+ }
229
+ catch (error) {
230
+ console.error(`Error writing file "${absoluteFilePath}": ${error.message}`);
231
+ throw error;
232
+ }
233
+ }
234
+ }
235
+ }
236
+ _GeneratedContentManager_instances = new WeakSet(), _GeneratedContentManager_getTarget = function _GeneratedContentManager_getTarget(targetName) {
237
+ const resolvedTargetName = (targetName || DEFAULT_TARGET.name);
238
+ if (!this.generatedContentMap.has(resolvedTargetName)) {
239
+ throw new Error(`Target "${resolvedTargetName}" is not registered`);
240
+ }
241
+ return this.targetMap.get(resolvedTargetName);
242
+ };
@@ -0,0 +1,2 @@
1
+ export * from './generated-content-manager.js';
2
+ export * from './tools.js';
@@ -0,0 +1,2 @@
1
+ export * from './generated-content-manager.js';
2
+ export * from './tools.js';
@@ -0,0 +1,9 @@
1
+ import { URI } from "langium";
2
+ /**
3
+ * Return workspace folder {URI} (if found) matching the document URI.
4
+ *
5
+ * @param {URI} [documentURI] document URI
6
+ * @param {URI[]} [workspaceURIs] a list of workspace URIs to consider. Optional
7
+ * @returns {URI} one of the URIs from <code>workspaceURIs</code> or <code>undefined</code>, if the document couldn't be matched to any workspaces.
8
+ */
9
+ export declare function getWorkspaceForDocument(documentURI?: URI, workspaceURIs?: URI[]): URI | undefined;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Return workspace folder {URI} (if found) matching the document URI.
3
+ *
4
+ * @param {URI} [documentURI] document URI
5
+ * @param {URI[]} [workspaceURIs] a list of workspace URIs to consider. Optional
6
+ * @returns {URI} one of the URIs from <code>workspaceURIs</code> or <code>undefined</code>, if the document couldn't be matched to any workspaces.
7
+ */
8
+ export function getWorkspaceForDocument(documentURI, workspaceURIs) {
9
+ return workspaceURIs === null || workspaceURIs === void 0 ? void 0 : workspaceURIs.find(workspaceURI => {
10
+ return documentURI === null || documentURI === void 0 ? void 0 : documentURI.toString().startsWith(workspaceURI.toString());
11
+ });
12
+ }
@@ -0,0 +1,4 @@
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';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
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';
@@ -0,0 +1 @@
1
+ export * as java from './java/index.js';
@@ -0,0 +1 @@
1
+ export * as java from './java/index.js';
@@ -0,0 +1 @@
1
+ export declare function packageToPath(packageName?: string): string | unknown;
@@ -0,0 +1,3 @@
1
+ export function packageToPath(packageName) {
2
+ return packageName === null || packageName === void 0 ? void 0 : packageName.replace(/\./g, "/");
3
+ }
@@ -0,0 +1,37 @@
1
+ import { CreateFileOptions, GeneratorManager } from "langium-tools/generator";
2
+ import { CompositeGeneratorNode } from "langium/generate";
3
+ /**
4
+ * Generates a Java source file with proper package declaration, imports, and body content.
5
+ *
6
+ * This function simplifies the generation of Java files by handling common boilerplate code such as
7
+ * package declarations and import statements. It leverages a `JavaImportManager` to manage imports
8
+ * automatically based on the classes used in the body content.
9
+ *
10
+ * @param {string} fileName - The name of the Java file to be generated (without the `.java` extension).
11
+ * @param {string} packageName - The package name for the Java file (e.g., `com.example.project`).
12
+ * @param {GeneratorManager} generatorManager - The manager responsible for handling file creation and output.
13
+ * @param {(importManager: (fqn: string) => string) => CompositeGeneratorNode} bodyGenerator - A function that generates
14
+ * the body of the Java file. It receives an `importManager` function to handle class imports and returns a `CompositeGeneratorNode`
15
+ * representing the body content.
16
+ * @param {CreateFileOptions} [options] - Optional settings for file creation, such as encoding or overwrite behavior.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * generateJavaFile(
21
+ * 'MyClass',
22
+ * 'com.example.project',
23
+ * generatorManager,
24
+ * (importClass) => expandToNode`
25
+ * public class MyClass {
26
+ * public ${imp('java.util.Properties')} getProperties() {
27
+ * // ...
28
+ * }
29
+ * }
30
+ * }`
31
+ * );
32
+ * ```
33
+ *
34
+ * The above example generates a Java class `MyClass` in the package `com.example.project`, with an imported `java.util.Properties`.
35
+ * The `imp` function handles the import management, ensuring that `java.util.Properties` is imported and conflicts are resolved.
36
+ */
37
+ export declare function generateJavaFile(fileName: string, packageName: string, generatorManager: GeneratorManager, bodyGenerator: (importManager: (fqn: string) => string) => CompositeGeneratorNode, options?: CreateFileOptions): void;
@@ -0,0 +1,48 @@
1
+ import { expandToNode, toString } from "langium/generate";
2
+ import { packageToPath } from "./common.js";
3
+ import { JavaImportManager } from "./import-manager.js";
4
+ /**
5
+ * Generates a Java source file with proper package declaration, imports, and body content.
6
+ *
7
+ * This function simplifies the generation of Java files by handling common boilerplate code such as
8
+ * package declarations and import statements. It leverages a `JavaImportManager` to manage imports
9
+ * automatically based on the classes used in the body content.
10
+ *
11
+ * @param {string} fileName - The name of the Java file to be generated (without the `.java` extension).
12
+ * @param {string} packageName - The package name for the Java file (e.g., `com.example.project`).
13
+ * @param {GeneratorManager} generatorManager - The manager responsible for handling file creation and output.
14
+ * @param {(importManager: (fqn: string) => string) => CompositeGeneratorNode} bodyGenerator - A function that generates
15
+ * the body of the Java file. It receives an `importManager` function to handle class imports and returns a `CompositeGeneratorNode`
16
+ * representing the body content.
17
+ * @param {CreateFileOptions} [options] - Optional settings for file creation, such as encoding or overwrite behavior.
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * generateJavaFile(
22
+ * 'MyClass',
23
+ * 'com.example.project',
24
+ * generatorManager,
25
+ * (importClass) => expandToNode`
26
+ * public class MyClass {
27
+ * public ${imp('java.util.Properties')} getProperties() {
28
+ * // ...
29
+ * }
30
+ * }
31
+ * }`
32
+ * );
33
+ * ```
34
+ *
35
+ * The above example generates a Java class `MyClass` in the package `com.example.project`, with an imported `java.util.Properties`.
36
+ * The `imp` function handles the import management, ensuring that `java.util.Properties` is imported and conflicts are resolved.
37
+ */
38
+ export function generateJavaFile(fileName, packageName, generatorManager, bodyGenerator, options) {
39
+ const importManager = new JavaImportManager(packageName);
40
+ const body = bodyGenerator(fqn => importManager.useClass(fqn));
41
+ generatorManager.createFile(`${packageToPath(packageName)}/${fileName}.java`, toString(expandToNode `
42
+ package ${packageName};
43
+
44
+ ${importManager.generateImports()}
45
+
46
+ ${body}
47
+ `), options);
48
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * A utility class for managing Java imports during code generation.
3
+ *
4
+ * This class simplifies the handling of Java imports by allowing you to register
5
+ * full qualified class names and ensuring that simple class names do not collide.
6
+ *
7
+ * ## Example
8
+ * ```typescript
9
+ * const importManager = new JavaImportManager();
10
+ *
11
+ * const code = `
12
+ * ${importManager.useClass('java.util.List');} list1;
13
+ * ${importManager.useClass('java.awt.List');} list2;
14
+ * `
15
+ * console.log(code);
16
+ * // Output:
17
+ * // List list1;
18
+ * // java.awt.List list2;
19
+ *
20
+ * console.log(importManager.generateImports());
21
+ * // Output:
22
+ * // import java.awt.List;
23
+ * ```
24
+ * Note, that the import manager will only generate imports for classes that are actually used.
25
+ * Conflicting class names will be resolved by using the full qualified name.
26
+ */
27
+ export declare class JavaImportManager {
28
+ readonly classes: Map<string, string>;
29
+ readonly currentPackage: string;
30
+ /**
31
+ * Creates a new Java import manager.
32
+ *
33
+ * @param {string} currentPackage - The current package to use. Classes from this package shouldn't be imported.
34
+ */
35
+ constructor(currentPackage?: string);
36
+ /**
37
+ * Registers a class for use in the generated Java code and returns a suitable name.
38
+ *
39
+ * If the simple name of the provided full qualified name is not already registered, this method
40
+ * registers it and returns the simple name. If a collision occurs (i.e., two different full
41
+ * qualified names share the same simple name), the method returns the full qualified name instead.
42
+ *
43
+ * This method should be called with the same full qualified name every time it is used in the generated code.
44
+ *
45
+ * @param {string} fullQualifiedName - The fully qualified name of the class (e.g., `java.util.List`).
46
+ * @returns {string} The name to use in the generated code, either the simple class name or the full qualified name.
47
+ */
48
+ useClass(fullQualifiedName: string): string;
49
+ /**
50
+ * Generates a list of Java import statements based on the registered classes.
51
+ *
52
+ * This method iterates over the registered classes and produces the corresponding
53
+ * import statements in alphabetical order. The result can be directly included at
54
+ * the beginning of a Java file.
55
+ *
56
+ * Method {@link useClass} shouldn't be called after this method.
57
+ *
58
+ * @returns {string} A formatted string containing all the import statements, separated by line breaks.
59
+ */
60
+ generateImports(): string;
61
+ }