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
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { EOL } from "node:os";
|
|
2
|
+
// TODO: Add support for java.lang without import
|
|
3
|
+
/**
|
|
4
|
+
* A utility class for managing Java imports during code generation.
|
|
5
|
+
*
|
|
6
|
+
* This class simplifies the handling of Java imports by allowing you to register
|
|
7
|
+
* full qualified class names and ensuring that simple class names do not collide.
|
|
8
|
+
*
|
|
9
|
+
* ## Example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* const importManager = new JavaImportManager();
|
|
12
|
+
*
|
|
13
|
+
* const code = `
|
|
14
|
+
* ${importManager.useClass('java.util.List');} list1;
|
|
15
|
+
* ${importManager.useClass('java.awt.List');} list2;
|
|
16
|
+
* `
|
|
17
|
+
* console.log(code);
|
|
18
|
+
* // Output:
|
|
19
|
+
* // List list1;
|
|
20
|
+
* // java.awt.List list2;
|
|
21
|
+
*
|
|
22
|
+
* console.log(importManager.generateImports());
|
|
23
|
+
* // Output:
|
|
24
|
+
* // import java.awt.List;
|
|
25
|
+
* ```
|
|
26
|
+
* Note, that the import manager will only generate imports for classes that are actually used.
|
|
27
|
+
* Conflicting class names will be resolved by using the full qualified name.
|
|
28
|
+
*/
|
|
29
|
+
export class JavaImportManager {
|
|
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 = "") {
|
|
36
|
+
this.classes = new Map();
|
|
37
|
+
this.currentPackage = currentPackage;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Registers a class for use in the generated Java code and returns a suitable name.
|
|
41
|
+
*
|
|
42
|
+
* If the simple name of the provided full qualified name is not already registered, this method
|
|
43
|
+
* registers it and returns the simple name. If a collision occurs (i.e., two different full
|
|
44
|
+
* qualified names share the same simple name), the method returns the full qualified name instead.
|
|
45
|
+
*
|
|
46
|
+
* This method should be called with the same full qualified name every time it is used in the generated code.
|
|
47
|
+
*
|
|
48
|
+
* @param {string} fullQualifiedName - The fully qualified name of the class (e.g., `java.util.List`).
|
|
49
|
+
* @returns {string} The name to use in the generated code, either the simple class name or the full qualified name.
|
|
50
|
+
*/
|
|
51
|
+
useClass(fullQualifiedName) {
|
|
52
|
+
const dotIndex = fullQualifiedName.lastIndexOf(".");
|
|
53
|
+
if (dotIndex === -1) {
|
|
54
|
+
return fullQualifiedName;
|
|
55
|
+
}
|
|
56
|
+
const name = fullQualifiedName.slice(dotIndex + 1);
|
|
57
|
+
const packageName = fullQualifiedName.slice(0, dotIndex);
|
|
58
|
+
if (packageName === this.currentPackage) {
|
|
59
|
+
if (!this.classes.has(name)) {
|
|
60
|
+
this.classes.set(name, "");
|
|
61
|
+
return name;
|
|
62
|
+
}
|
|
63
|
+
else if (this.classes.get(name) === "") {
|
|
64
|
+
return name;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (!this.classes.has(name)) {
|
|
68
|
+
this.classes.set(name, fullQualifiedName);
|
|
69
|
+
return name;
|
|
70
|
+
}
|
|
71
|
+
const importedFQN = this.classes.get(name);
|
|
72
|
+
return (importedFQN === fullQualifiedName) ? name : fullQualifiedName;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Generates a list of Java import statements based on the registered classes.
|
|
76
|
+
*
|
|
77
|
+
* This method iterates over the registered classes and produces the corresponding
|
|
78
|
+
* import statements in alphabetical order. The result can be directly included at
|
|
79
|
+
* the beginning of a Java file.
|
|
80
|
+
*
|
|
81
|
+
* Method {@link useClass} shouldn't be called after this method.
|
|
82
|
+
*
|
|
83
|
+
* @returns {string} A formatted string containing all the import statements, separated by line breaks.
|
|
84
|
+
*/
|
|
85
|
+
generateImports() {
|
|
86
|
+
return Array.from(this.classes.values()).filter(fqn => fqn.length > 0).map(fqn => `import ${fqn};`).sort().join(EOL);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function using<T>(obj: T, block: (it: T) => void): T;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { AstNode, LangiumDocument, WorkspaceFolder } from 'langium';
|
|
2
|
+
import { type DefaultSharedModuleContext, type LangiumSharedServices } from 'langium/lsp';
|
|
3
|
+
import { GeneratorManager, GeneratedContentManager, GeneratorTarget } from '../generator/generated-content-manager.js';
|
|
4
|
+
type DslServices<SERVICES, SHARED_SERVICES> = {
|
|
5
|
+
shared: LangiumSharedServices & SHARED_SERVICES;
|
|
6
|
+
} & SERVICES;
|
|
7
|
+
type ValueOf<T> = T[keyof T];
|
|
8
|
+
type ExtractServiceType<T> = ValueOf<Omit<T, 'shared'>>;
|
|
9
|
+
export declare enum GeneratorMode {
|
|
10
|
+
Generate = 0,
|
|
11
|
+
Verify = 1
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Metadata for generated files.
|
|
15
|
+
* Saved in the output directory of corresponding output directory.
|
|
16
|
+
*/
|
|
17
|
+
export interface GeneratorTestOutputDirectoryMetadata {
|
|
18
|
+
generatedFiles: {
|
|
19
|
+
filename: string;
|
|
20
|
+
overwrite: boolean;
|
|
21
|
+
}[];
|
|
22
|
+
}
|
|
23
|
+
export interface GeneratorTestOptions<SERVICES, SHARED_SERVICES, MODEL extends AstNode> {
|
|
24
|
+
generateMode?: GeneratorMode;
|
|
25
|
+
createServices: (context: DefaultSharedModuleContext) => DslServices<SERVICES, SHARED_SERVICES>;
|
|
26
|
+
initWorkspace?: (service: DslServices<SERVICES, SHARED_SERVICES>, workspaceDir: string) => Promise<WorkspaceFolder>;
|
|
27
|
+
buildDocuments?: (service: DslServices<SERVICES, SHARED_SERVICES>, workspaceFolder: WorkspaceFolder) => Promise<LangiumDocument<AstNode>[]>;
|
|
28
|
+
validateDocuments?: (service: DslServices<SERVICES, SHARED_SERVICES>, documents: LangiumDocument<AstNode>[]) => Promise<LangiumDocument<AstNode>[]>;
|
|
29
|
+
generateForWorkspace?: (service: DslServices<SERVICES, SHARED_SERVICES>, documents: LangiumDocument<AstNode>[], workspaceFolder: WorkspaceFolder, targets?: GeneratorTarget[]) => Promise<GeneratedContentManager>;
|
|
30
|
+
generateForModel?: (services: ExtractServiceType<SERVICES>, document: MODEL, generatorOutput: GeneratorManager) => Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Run generator snapshot tests for all workspaces (subdirectories of the `testSuiteDir` directory).
|
|
34
|
+
* For each workspace there will be a tests added to vitest suite.
|
|
35
|
+
*
|
|
36
|
+
* @param testSuiteDir directory with the workspace directories (as direct subdirectories to `testSuiteDir`)
|
|
37
|
+
* @param options options
|
|
38
|
+
* @param targets optional list of additional target directories (Xtext outlets) to be supported by the generator (generator provided in `options`).
|
|
39
|
+
*/
|
|
40
|
+
export declare function langiumGeneratorSuite<SERVICES, SHARED_SERVICES, MODEL extends AstNode>(testSuiteDir: string, options: GeneratorTestOptions<SERVICES, SHARED_SERVICES, MODEL>, targets?: GeneratorTarget[]): void;
|
|
41
|
+
/**
|
|
42
|
+
* Run generator test for a single DSL workspace.
|
|
43
|
+
*
|
|
44
|
+
* @param testDir The directory containing the DSL workspace.
|
|
45
|
+
* @param options The generator test options.
|
|
46
|
+
* @param targets Optional list of custom generator targets to be used by the generator.
|
|
47
|
+
*/
|
|
48
|
+
export declare function langiumGeneratorTest<SERVICES, SHARED_SERVICES, MODEL extends AstNode>(testDir: string, options: GeneratorTestOptions<SERVICES, SHARED_SERVICES, MODEL>, targets?: GeneratorTarget[]): Promise<void>;
|
|
49
|
+
export declare function defaultInitWorkspace({ shared }: {
|
|
50
|
+
shared: LangiumSharedServices;
|
|
51
|
+
}, workspaceDir: string): Promise<WorkspaceFolder>;
|
|
52
|
+
export declare function defaultBuildDocuments({ shared }: {
|
|
53
|
+
shared: LangiumSharedServices;
|
|
54
|
+
}, workspaceFolder: WorkspaceFolder): Promise<LangiumDocument<AstNode>[]>;
|
|
55
|
+
export declare function defaultValidateDocuments(_service: object, documents: LangiumDocument<AstNode>[]): Promise<void>;
|
|
56
|
+
export {};
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { URI } from 'langium';
|
|
2
|
+
import { NodeFileSystem } from 'langium/node';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import fs from 'fs';
|
|
5
|
+
import { expect, test } from 'vitest';
|
|
6
|
+
import { getDocumentIssueSummary } from '../base/document-issues.js';
|
|
7
|
+
import { GeneratedContentManager, DEFAULT_TARGET } from '../generator/generated-content-manager.js';
|
|
8
|
+
export var GeneratorMode;
|
|
9
|
+
(function (GeneratorMode) {
|
|
10
|
+
GeneratorMode[GeneratorMode["Generate"] = 0] = "Generate";
|
|
11
|
+
GeneratorMode[GeneratorMode["Verify"] = 1] = "Verify";
|
|
12
|
+
})(GeneratorMode || (GeneratorMode = {}));
|
|
13
|
+
;
|
|
14
|
+
const globalGenerateMode = process.env.GENERATOR_TEST === "generate" ? GeneratorMode.Generate : GeneratorMode.Verify;
|
|
15
|
+
/**
|
|
16
|
+
* Run generator snapshot tests for all workspaces (subdirectories of the `testSuiteDir` directory).
|
|
17
|
+
* For each workspace there will be a tests added to vitest suite.
|
|
18
|
+
*
|
|
19
|
+
* @param testSuiteDir directory with the workspace directories (as direct subdirectories to `testSuiteDir`)
|
|
20
|
+
* @param options options
|
|
21
|
+
* @param targets optional list of additional target directories (Xtext outlets) to be supported by the generator (generator provided in `options`).
|
|
22
|
+
*/
|
|
23
|
+
export function langiumGeneratorSuite(testSuiteDir, options, targets) {
|
|
24
|
+
const { generateMode = globalGenerateMode } = options;
|
|
25
|
+
fs.readdirSync(testSuiteDir, { withFileTypes: true })
|
|
26
|
+
.filter((dirent) => dirent.isDirectory())
|
|
27
|
+
.forEach((dirent) => {
|
|
28
|
+
const testDirName = dirent.name;
|
|
29
|
+
test(`DSL-Workspace "${testDirName}"${generateMode ? ' (generating)' : ''}`, async () => {
|
|
30
|
+
await langiumGeneratorTest(path.join(testSuiteDir, testDirName), options, targets);
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Run generator test for a single DSL workspace.
|
|
36
|
+
*
|
|
37
|
+
* @param testDir The directory containing the DSL workspace.
|
|
38
|
+
* @param options The generator test options.
|
|
39
|
+
* @param targets Optional list of custom generator targets to be used by the generator.
|
|
40
|
+
*/
|
|
41
|
+
export async function langiumGeneratorTest(testDir, options, targets) {
|
|
42
|
+
async function defaultGenerateForWorkspace(services, documents, workspaceFolder, targets) {
|
|
43
|
+
const optionsGenerator = options.generateForModel;
|
|
44
|
+
if (!optionsGenerator) {
|
|
45
|
+
throw new Error('One of generateForDocument or generateForWorkspace must be defined');
|
|
46
|
+
}
|
|
47
|
+
const generatedContentManager = new GeneratedContentManager([workspaceFolder.uri]);
|
|
48
|
+
targets === null || targets === void 0 ? void 0 : targets.forEach(target => generatedContentManager.addTarget(target));
|
|
49
|
+
for (const document of documents) {
|
|
50
|
+
const model = document.parseResult.value;
|
|
51
|
+
const nonSharedServices = Object.keys(services).filter(key => key !== 'shared');
|
|
52
|
+
if (nonSharedServices.length !== 1) {
|
|
53
|
+
throw new Error('Expected exactly one non-shared service');
|
|
54
|
+
}
|
|
55
|
+
const serviceName = nonSharedServices[0];
|
|
56
|
+
await optionsGenerator(services[serviceName], model, generatedContentManager.generatorManagerFor(model));
|
|
57
|
+
}
|
|
58
|
+
return generatedContentManager;
|
|
59
|
+
}
|
|
60
|
+
const { initWorkspace = defaultInitWorkspace, buildDocuments = defaultBuildDocuments, validateDocuments = defaultValidateDocuments, generateForWorkspace = defaultGenerateForWorkspace, generateMode = globalGenerateMode, } = options;
|
|
61
|
+
const services = options.createServices(NodeFileSystem);
|
|
62
|
+
const workspaceFolder = await initWorkspace(services, testDir);
|
|
63
|
+
const documents = await buildDocuments(services, workspaceFolder);
|
|
64
|
+
await validateDocuments(services, documents);
|
|
65
|
+
const generatedContentManager = await generateForWorkspace(services, documents, workspaceFolder, targets);
|
|
66
|
+
const outputDir = path.join(testDir, 'generated');
|
|
67
|
+
const dirsAndTargets = (targets === null || targets === void 0 ? void 0 : targets.length) ? generatedContentManager.getTargets().map(target => ({
|
|
68
|
+
dir: path.join(outputDir, target.name),
|
|
69
|
+
metadataFile: path.join(testDir, `${target.name}-metadata.json`),
|
|
70
|
+
target,
|
|
71
|
+
})) : [{
|
|
72
|
+
dir: outputDir,
|
|
73
|
+
metadataFile: path.join(testDir, 'generated-metadata.json'),
|
|
74
|
+
target: DEFAULT_TARGET,
|
|
75
|
+
}];
|
|
76
|
+
if (generateMode === GeneratorMode.Generate) {
|
|
77
|
+
cleanDir(outputDir);
|
|
78
|
+
for (const { dir, metadataFile, target } of dirsAndTargets) {
|
|
79
|
+
await generatedContentManager.writeToDisk(dir, target.name);
|
|
80
|
+
writeMetaData(generatedContentManager, metadataFile, target.name);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
else {
|
|
84
|
+
for (const { dir, metadataFile, target } of dirsAndTargets) {
|
|
85
|
+
verifyFiles(generatedContentManager.getGeneratedContent(target.name), dir, target.name);
|
|
86
|
+
verifyMetaData(generatedContentManager, metadataFile, target.name);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
export async function defaultInitWorkspace({ shared }, workspaceDir) {
|
|
91
|
+
const workspaceManager = shared.workspace.WorkspaceManager;
|
|
92
|
+
const workspaceFolder = {
|
|
93
|
+
name: 'MyDSL Workspace',
|
|
94
|
+
uri: URI.file(workspaceDir).toString()
|
|
95
|
+
};
|
|
96
|
+
await workspaceManager.initializeWorkspace([workspaceFolder]);
|
|
97
|
+
return workspaceFolder;
|
|
98
|
+
}
|
|
99
|
+
export async function defaultBuildDocuments({ shared }, workspaceFolder) {
|
|
100
|
+
const LangiumDocuments = shared.workspace.LangiumDocuments;
|
|
101
|
+
const DocumentBuilder = shared.workspace.DocumentBuilder;
|
|
102
|
+
const documents = LangiumDocuments.all.toArray();
|
|
103
|
+
console.log(`Building workspace ${workspaceFolder.uri} with ${documents.length} DSLs`);
|
|
104
|
+
await DocumentBuilder.build(documents, { validation: true });
|
|
105
|
+
return documents;
|
|
106
|
+
}
|
|
107
|
+
export async function defaultValidateDocuments(_service, documents) {
|
|
108
|
+
documents.forEach(doc => {
|
|
109
|
+
const summary = getDocumentIssueSummary(doc, { skipValidation: true });
|
|
110
|
+
if (summary.countTotal > 0) {
|
|
111
|
+
expect(summary.summary, `DSL file ${doc.uri} has errors:\n${summary.message}`).toBe('No errors');
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Clean output directory.
|
|
117
|
+
*
|
|
118
|
+
* Make sure not to delete files that are not generated by the generator
|
|
119
|
+
* by checking sibling directories. The dsls directory should be present
|
|
120
|
+
* in the same directory as the out directory.
|
|
121
|
+
*
|
|
122
|
+
* @param outputDir
|
|
123
|
+
*/
|
|
124
|
+
function cleanDir(outputDir) {
|
|
125
|
+
if (!fs.existsSync(outputDir)) {
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const siblingDirs = fs.readdirSync(path.join(outputDir, ".."));
|
|
129
|
+
if (!siblingDirs.includes("dsls")) {
|
|
130
|
+
throw new Error(`The out directory ${outputDir} should have a sibling directory named 'dsls'`);
|
|
131
|
+
}
|
|
132
|
+
const files = fs.readdirSync(outputDir);
|
|
133
|
+
files.forEach((file) => {
|
|
134
|
+
fs.rmSync(path.join(outputDir, file), { recursive: true });
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Verify, that generated file structure matches exacly
|
|
139
|
+
* with the existing files in the output directory.
|
|
140
|
+
*
|
|
141
|
+
* @param fileContentMap
|
|
142
|
+
* @param outputDir
|
|
143
|
+
*/
|
|
144
|
+
function verifyFiles(generatedContent, outputDir, target) {
|
|
145
|
+
const files = fs.readdirSync(outputDir, { recursive: true })
|
|
146
|
+
.filter(file => fs.statSync(path.join(outputDir, file)).isFile())
|
|
147
|
+
.map(path.normalize);
|
|
148
|
+
const targetDescription = target == DEFAULT_TARGET.name ? "" : ` for target '${target}'`;
|
|
149
|
+
generatedContent.forEach((content, fileName) => {
|
|
150
|
+
const normFileName = path.normalize(fileName);
|
|
151
|
+
expect(files, `Unexpected generated file${targetDescription}: ${normFileName}`).toContain(normFileName);
|
|
152
|
+
const filePath = path.join(outputDir, normFileName);
|
|
153
|
+
const fileContent = fs.readFileSync(filePath, "utf-8");
|
|
154
|
+
expect(content.content, `File${targetDescription}: ${fileName}`).toBe(fileContent);
|
|
155
|
+
});
|
|
156
|
+
const generatedFiles = Array.from(generatedContent.keys()).map(path.normalize);
|
|
157
|
+
expect(files.length, `Missing generated file(s)${targetDescription}: ${files.filter((file) => !generatedFiles.includes(file)).join(", ")}`).toBe(generatedContent.size);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Write metadata from generated content to the output directory.
|
|
161
|
+
*/
|
|
162
|
+
function writeMetaData(generatedContent, metadataJsonFile, target) {
|
|
163
|
+
const metadata = {
|
|
164
|
+
generatedFiles: []
|
|
165
|
+
};
|
|
166
|
+
generatedContent.getGeneratedContent(target).forEach((contentData, fileName) => {
|
|
167
|
+
metadata.generatedFiles.push({ filename: fileName, overwrite: contentData.overwrite });
|
|
168
|
+
});
|
|
169
|
+
fs.writeFileSync(metadataJsonFile, JSON.stringify(metadata, null, 2));
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Verify metadata from generated content agains metadata file.
|
|
173
|
+
*/
|
|
174
|
+
function verifyMetaData(generatedContent, metadataJsonFile, target) {
|
|
175
|
+
const metadata = JSON.parse(fs.readFileSync(metadataJsonFile, 'utf-8'));
|
|
176
|
+
const generatedFiles = generatedContent.getGeneratedContent(target);
|
|
177
|
+
const targetDescription = target == DEFAULT_TARGET.name ? "" : ` for target '${target}'`;
|
|
178
|
+
metadata.generatedFiles.forEach((metadataFile) => {
|
|
179
|
+
const contentData = generatedFiles.get(metadataFile.filename);
|
|
180
|
+
expect(contentData, `File${targetDescription}: ${metadataFile.filename}`).toBeDefined();
|
|
181
|
+
expect(contentData === null || contentData === void 0 ? void 0 : contentData.overwrite, `File${targetDescription}: ${metadataFile.filename}. Overwrite flag was changed`).toBe(metadataFile.overwrite);
|
|
182
|
+
});
|
|
183
|
+
expect(metadata.generatedFiles.length, `Missmatch in amount of generated files and metadata${targetDescription}`).toBe(generatedFiles.size);
|
|
184
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import 'vitest';
|
|
2
|
+
import { LangiumDocument } from "langium";
|
|
3
|
+
import { DocumentIssueSeverity, DocumentIssueSource } from "../base/document-issues.js";
|
|
4
|
+
import { ParsedDocument } from './parser-tools.js';
|
|
5
|
+
/**
|
|
6
|
+
* Parameters to customize which types of issues to ignore during document validation.
|
|
7
|
+
*/
|
|
8
|
+
export interface IgnoreParameters {
|
|
9
|
+
/** Whether to ignore parser errors. Default is `false`. */
|
|
10
|
+
ignoreParserErrors?: boolean;
|
|
11
|
+
/** Whether to ignore lexer errors. Default is `false`. */
|
|
12
|
+
ignoreLexerErrors?: boolean;
|
|
13
|
+
/** Whether to ignore validation errors. Default is `false`. */
|
|
14
|
+
ignoreValidationErrors?: boolean;
|
|
15
|
+
/** Whether to ignore non-error diagnostics (e.g., warnings, hints). Default is `false`. */
|
|
16
|
+
ignoreNonErrorDiagnostics?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Expects a Langium document to have no errors after parsing.
|
|
20
|
+
* Non-error diagnostics are ignored by default.
|
|
21
|
+
*
|
|
22
|
+
* @param document - The Langium document or parsed document to check for errors.
|
|
23
|
+
* @param parameters - Optional parameters to customize which errors to ignore.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* import { expect, test } from 'vitest';
|
|
28
|
+
* import { parse } from './your-langium-test-setup';
|
|
29
|
+
*
|
|
30
|
+
* test('document has no errors', async () => {
|
|
31
|
+
* const doc = await parse('const x = 5;');
|
|
32
|
+
* expect(doc).toHaveNoErrors();
|
|
33
|
+
* });
|
|
34
|
+
*
|
|
35
|
+
* test('document has no errors, ignoring lexer errors', async () => {
|
|
36
|
+
* const doc = await parse('const x = @;', { validation: true });
|
|
37
|
+
* expect(doc).toHaveNoErrors({ ignoreLexerErrors: true });
|
|
38
|
+
* });
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export declare function toHaveNoErrors(document: LangiumDocument | ParsedDocument, parameters?: IgnoreParameters): {
|
|
42
|
+
pass: boolean;
|
|
43
|
+
message: () => string;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Expects a Langium document to have no issues after parsing.
|
|
47
|
+
*
|
|
48
|
+
* @param document - The Langium document or parsed document to check for issues.
|
|
49
|
+
* @param parameters - Optional parameters to customize which issues to ignore.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```typescript
|
|
53
|
+
* import { expect, test } from 'vitest';
|
|
54
|
+
* import { parse } from './your-langium-test-setup';
|
|
55
|
+
*
|
|
56
|
+
* test('document has no issues', async () => {
|
|
57
|
+
* const doc = await parse('const x = 5;');
|
|
58
|
+
* expect(doc).toHaveNoIssues();
|
|
59
|
+
* });
|
|
60
|
+
*
|
|
61
|
+
* test('document has no issues, ignoring lexer errors', async () => {
|
|
62
|
+
* const doc = await parse('const x = @;', { validation: true });
|
|
63
|
+
* expect(doc).toHaveNoIssues({ ignoreLexerErrors: true });
|
|
64
|
+
* });
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export declare function toHaveNoIssues(document: LangiumDocument | ParsedDocument, parameters?: IgnoreParameters): {
|
|
68
|
+
pass: boolean;
|
|
69
|
+
message: () => string;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Represents an expected issue in a Langium document.
|
|
73
|
+
*/
|
|
74
|
+
export interface IssueExpectation {
|
|
75
|
+
/**
|
|
76
|
+
* The severity of the issue.
|
|
77
|
+
* Defaults to `DocumentIssueSeverity.ERROR` if not specified.
|
|
78
|
+
*/
|
|
79
|
+
severity?: DocumentIssueSeverity;
|
|
80
|
+
/**
|
|
81
|
+
* The source of the issue (lexer, parser, validator, etc.).
|
|
82
|
+
* Not asserted if not provided.
|
|
83
|
+
*/
|
|
84
|
+
source?: DocumentIssueSource;
|
|
85
|
+
/**
|
|
86
|
+
* The expected message of the issue.
|
|
87
|
+
* Can be a string or a regular expression to match against the actual message.
|
|
88
|
+
*/
|
|
89
|
+
message: string | RegExp;
|
|
90
|
+
/**
|
|
91
|
+
* 0-based marker ID in the DSL.
|
|
92
|
+
* Not asserted if not provided.
|
|
93
|
+
*/
|
|
94
|
+
markerId?: number;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Expects a parsed Langium document with markers to have specific issues.
|
|
98
|
+
*
|
|
99
|
+
* @param parsedDocument - The parsed Langium document with markers to check for issues.
|
|
100
|
+
* @param expectedIssues - An array of expected issues.
|
|
101
|
+
* @param parameters - Optional parameters to customize which issues to ignore.
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```typescript
|
|
105
|
+
* import { expect, test } from 'vitest';
|
|
106
|
+
* import { parseDocument } from './your-langium-test-setup';
|
|
107
|
+
*
|
|
108
|
+
* test('document has expected issues', async () => {
|
|
109
|
+
* const parsedDoc = await parseMarkedDSL(`
|
|
110
|
+
* let [[x: string]] = 5;
|
|
111
|
+
* print(x);
|
|
112
|
+
* `, '[[', ']]');
|
|
113
|
+
* expect(parsedDoc).toHaveDocumentIssues([
|
|
114
|
+
* {
|
|
115
|
+
* message: "Type 'number' is not assignable to type 'string'",
|
|
116
|
+
* markerId: 0
|
|
117
|
+
* }
|
|
118
|
+
* ]);
|
|
119
|
+
* });
|
|
120
|
+
*
|
|
121
|
+
* test('document has a warning, ignoring errors', async () => {
|
|
122
|
+
* const parsedDoc = await parseMarkedDSL(`
|
|
123
|
+
* let [[foo]];
|
|
124
|
+
* `, '[[', ']]');
|
|
125
|
+
* expect(parsedDoc).toHaveDocumentIssues(
|
|
126
|
+
* [
|
|
127
|
+
* {
|
|
128
|
+
* severity: DocumentIssueSeverity.WARNING,
|
|
129
|
+
* message: "Variable 'foo' is never used",
|
|
130
|
+
* markerId: 0
|
|
131
|
+
* }
|
|
132
|
+
* ],
|
|
133
|
+
* { ignoreValidationErrors: true }
|
|
134
|
+
* );
|
|
135
|
+
* });
|
|
136
|
+
* ```
|
|
137
|
+
*/
|
|
138
|
+
export declare function toHaveDocumentIssues(parsedDocument: ParsedDocument, expectedIssues: Array<IssueExpectation>, parameters?: IgnoreParameters): {
|
|
139
|
+
pass: boolean;
|
|
140
|
+
message: () => string;
|
|
141
|
+
};
|
|
142
|
+
/**
|
|
143
|
+
* Expects that a specific issue is present in the Langium document.
|
|
144
|
+
*
|
|
145
|
+
* @param document - The Langium document or parsed document to check for the issue.
|
|
146
|
+
* @param expectedIssue - The expected issue to look for.
|
|
147
|
+
* @param parameters - Optional parameters to customize which issues to ignore.
|
|
148
|
+
*
|
|
149
|
+
* @example
|
|
150
|
+
* ```typescript
|
|
151
|
+
* import { expect, test } from 'vitest';
|
|
152
|
+
* import { parse } from './your-langium-test-setup';
|
|
153
|
+
*
|
|
154
|
+
* test('document contains specific issue', async () => {
|
|
155
|
+
* const doc = await parse('const x = @;', { validation: true });
|
|
156
|
+
* expect(doc).toContainIssue({
|
|
157
|
+
* message: /Unexpected character/,
|
|
158
|
+
* severity: DocumentIssueSeverity.ERROR,
|
|
159
|
+
* source: DocumentIssueSource.LEXER,
|
|
160
|
+
* });
|
|
161
|
+
* });
|
|
162
|
+
* ```
|
|
163
|
+
*/
|
|
164
|
+
export declare function toContainIssue(document: LangiumDocument | ParsedDocument, expectedIssue: IssueExpectation, parameters?: IgnoreParameters): {
|
|
165
|
+
pass: boolean;
|
|
166
|
+
message: () => string;
|
|
167
|
+
};
|
|
168
|
+
/**
|
|
169
|
+
* Interface extending Vitest's matchers with Langium-specific assertions.
|
|
170
|
+
*/
|
|
171
|
+
interface LangiumMatchers<R = unknown> {
|
|
172
|
+
/**
|
|
173
|
+
* Asserts that a document has no errors after parsing.
|
|
174
|
+
* Non-error diagnostics (warnings, hints) are ignored by default.
|
|
175
|
+
*
|
|
176
|
+
* @param parameters - Optional parameters to customize which errors to ignore.
|
|
177
|
+
*/
|
|
178
|
+
toHaveNoErrors: R extends LangiumDocument | ParsedDocument ? (parameters?: IgnoreParameters) => void : never;
|
|
179
|
+
/**
|
|
180
|
+
* Asserts that a document has no issues after parsing.
|
|
181
|
+
*
|
|
182
|
+
* @param parameters - Optional parameters to customize which issues to ignore.
|
|
183
|
+
*/
|
|
184
|
+
toHaveNoIssues: R extends LangiumDocument | ParsedDocument ? (parameters?: IgnoreParameters) => void : never;
|
|
185
|
+
/**
|
|
186
|
+
* Asserts that a parsed document has specific issues at specified markers.
|
|
187
|
+
*
|
|
188
|
+
* @param expectedIssues - An array of expected issues.
|
|
189
|
+
* @param parameters - Optional parameters to customize which issues to ignore.
|
|
190
|
+
*/
|
|
191
|
+
toHaveDocumentIssues: R extends ParsedDocument ? (expectedIssues: Array<IssueExpectation>, parameters?: IgnoreParameters) => void : never;
|
|
192
|
+
/**
|
|
193
|
+
* Asserts that a document contains a specific issue.
|
|
194
|
+
*
|
|
195
|
+
* @param expectedIssue - The expected issue to look for.
|
|
196
|
+
* @param parameters - Optional parameters to customize which issues to ignore.
|
|
197
|
+
*/
|
|
198
|
+
toContainIssue: R extends LangiumDocument | ParsedDocument ? (expectedIssue: IssueExpectation, parameters?: IgnoreParameters) => void : never;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Augments Vitest's assertion interface with Langium-specific matchers.
|
|
202
|
+
*/
|
|
203
|
+
declare module 'vitest' {
|
|
204
|
+
interface Assertion<T> extends LangiumMatchers<T> {
|
|
205
|
+
}
|
|
206
|
+
interface AsymmetricMatchersContaining<R = unknown> extends LangiumMatchers<R> {
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
export {};
|