diff --git a/README.md b/README.md index ff6801a..4595b92 100644 --- a/README.md +++ b/README.md @@ -121,8 +121,10 @@ Genmodels are not uploaded; they are generated from the metamodels. The pipeline 1. Validates the uploads (non-empty, expected extension, unique names). 2. Loads the metamodels, resolves references between them (relative, `platform:/resource`, or nsURI), - validates them with EMF, and generates matching genmodels. -3. Checks that every Reactions `import` refers to an uploaded nsURI. + validates them with EMF, rejects names whose generated Java code does not compile, and generates + matching genmodels. +3. Checks the reactions against the loaded metamodels: every `import` refers to an uploaded nsURI, and + aliases, classes, and trigger features exist and fit (see [Checks before the build](#checks-before-the-build)). 4. Generates a project following the [Methodologist Template](https://github.com/vitruv-tools/Methodologist-Template) (`model`, `consistency`, `vsum`), with a smoke test that creates and reloads the VSUM and compiles the constraints. 5. Runs `mvn clean verify`. @@ -144,17 +146,18 @@ contains the same as readable text: ```json { - "errorCode": "VSUM_BUILD_FAILED", - "status": 422, - "message": "The VSUM build failed:\n\nmy.reactions:\n- line 51, column 30: 'Entitiy' cannot be resolved\n...", + "errorCode": "VSUM_REACTIONS_ERROR", + "status": 400, + "message": "The uploaded reactions do not match the uploaded metamodels:\n\nmy.reactions:\n- line 51, column 30: ...", "problems": [ { "source": "REACTIONS", "file": "my.reactions", "line": 51, "column": 30, - "message": "'Entitiy' cannot be resolved", - "excerpt": " val entity = new model2::Entitiy\n ^" + "message": "'Entitiy' is not a class of the metamodel 'model2' (http://vitruv.tools/methodologisttemplate/model2)", + "excerpt": " val entity = new model2::Entitiy\n ^", + "hint": "Did you mean 'Entity'?" } ] } @@ -167,6 +170,41 @@ but counted in `hiddenFollowUpErrors`. Problems are reported for metamodels and the build, for Reactions compiler and Java compiler errors, and for failures of the smoke test (constraints that cannot be evaluated, exceptions in reactions or routines while creating the VSUM). +### Checks before the build + +Most mistakes are found in milliseconds, before Maven runs, and come with a suggestion: + +- **Metamodels**: EMF validation, with messages naming the element (`Thing.untyped`) and a hint; names + that differ only in upper/lower case or `_` (classes, features including inherited ones, enum + literals), Java reserved words as class names (`class`, `record`, `var`), and classes named like the + generated `Package`/`Factory` interfaces. EMF escapes reserved words in feature, + literal, and package names, so these are accepted. +- **Reactions**: aliases in segment headers and before `::`, `alias::Class` (including subpackages and + `using qualified names`), `[feature]` in triggers (attribute for `after attribute`, reference for + `after element`, single-valued for `replaced at`, many-valued for `inserted in`/`removed from`, and an + element type that fits the reference), and abstract classes, interfaces, or enums in `create` blocks. + +Errors only the Reactions compiler finds (syntax, Xbase expressions) are reported after the build, with a +hint from a catalog of compiler messages (`CompilerHints`). + +#### Dependency on the Reactions language + +The reactions checks (`ReactionsChecker`) do not use the Reactions language +(`tools.vitruv.dsls.reactions.language`); they reimplement the rules of its grammar +(`ReactionsLanguage.xtext`), scope provider (`CommonLanguageElementsScopeProvider`, +`ReactionsLanguageScopeProvider`), and validator (`ReactionsLanguageValidator`) in +[Vitruv-DSLs](https://github.com/vitruv-tools/Vitruv-DSLs), as of version 4.0.0. When +`setup.vsum.vitruv-dsls-version` is raised, compare these files with the version the checks follow and +adapt `ReactionsChecker` and `CompilerHints`. The checks only report what is certainly wrong and leave +everything else to the compiler, so a newer language can at worst make them miss a mistake; a failure of +the checker itself is logged and leaves the decision to the compiler. + +The language is deliberately not a dependency of the service: it brings Xtext/Xbase, Guice, ANTLR 3, +log4j-core, and Eclipse p2 wrappers, which conflict with Spring Boot's logging and dependency versions. +Linking Xbase expressions also needs the Java classes generated from the metamodels, which exist only after +the Maven build. Parsing with the real grammar before the build would therefore run in a separate JVM on the +jars the warm-up build puts into the Maven repository of the image. + The workspaces of `503` and `500` builds are kept in the temporary directory for debugging and deleted on a later startup once older than `setup.vsum.workspace-retention`. diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/EcoreDiagnostics.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/EcoreDiagnostics.java new file mode 100644 index 0000000..0ed233a --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/EcoreDiagnostics.java @@ -0,0 +1,167 @@ +package tools.vitruv.methodologist.setup.vsum.service.metamodel; + +import java.util.List; +import java.util.Optional; +import org.eclipse.emf.common.util.Diagnostic; +import org.eclipse.emf.ecore.ENamedElement; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EcorePackage; +import org.eclipse.emf.ecore.util.EcoreUtil; +import org.eclipse.emf.ecore.util.EcoreValidator; + +/** + * Turns the diagnostics of EMF's {@link EcoreValidator} into problems a methodologist can act on: + * object dumps are replaced by element names, redundant diagnostics are dropped, and a hint says + * how to fix the metamodel. + */ +final class EcoreDiagnostics { + + /** + * A metamodel problem found by validation. + * + * @param element the element to locate the problem at + * @param message what is wrong, without the element name + * @param hint how to fix it, or {@code null} + */ + record Finding(EObject element, String message, String hint) {} + + private EcoreDiagnostics() {} + + /** + * Translates a leaf diagnostic. + * + * @param diagnostic a diagnostic without children + * @return the problem, or empty if the diagnostic does not break the build or repeats another + */ + static Optional translate(Diagnostic diagnostic) { + List elements = + diagnostic.getData().stream() + .filter(EObject.class::isInstance) + .map(EObject.class::cast) + .filter(object -> !isEcoreMetamodel(object)) + .toList(); + if (diagnostic.getSeverity() == Diagnostic.WARNING && isNameClash(diagnostic)) { + return Optional.of(nameClash(diagnostic.getCode(), elements)); + } + if (diagnostic.getSeverity() < Diagnostic.ERROR || isMissingTypeOfTypedElement(diagnostic)) { + return Optional.empty(); + } + + String message = diagnostic.getMessage(); + for (EObject element : elements) { + message = message.replace(element.toString(), EcoreLocations.elementPath(element)); + } + EObject element = elements.isEmpty() ? null : elements.get(0); + String hint = null; + if (EcoreValidator.DIAGNOSTIC_SOURCE.equals(diagnostic.getSource())) { + switch (diagnostic.getCode()) { + case EcoreValidator.WELL_FORMED_NAME -> + hint = + "Names must be valid Java identifiers: letters, digits and '_', not starting with" + + " a digit"; + case EcoreValidator.WELL_FORMED_INSTANCE_TYPE_NAME -> { + if (message.contains("'null'")) { + message = "the data type has no instance type name"; + } + hint = + "Set the instance type name to a Java type such as java.lang.String, or use an" + + " Ecore data type such as EString instead"; + } + case EcoreValidator.VALID_TYPE -> + hint = + "Set the type, e.g. EString for an attribute or a class of the metamodels for a" + + " reference"; + case EcoreValidator.UNIQUE_FEATURE_NAMES -> + hint = "Features are inherited from the super types; rename one of them"; + case EcoreValidator.UNIQUE_CLASSIFIER_NAMES, + EcoreValidator.UNIQUE_ENUMERATOR_NAMES, + EcoreValidator.UNIQUE_SUBPACKAGE_NAMES -> + hint = "Rename one of them"; + case EcoreValidator.NO_CIRCULAR_SUPER_TYPES -> + hint = "Remove the super type that leads back to this class"; + case EcoreValidator.INTERFACE_IS_ABSTRACT -> + hint = "Make the class abstract as well, or clear 'interface'"; + case EcoreValidator.CONSISTENT_OPPOSITE_NOT_FROM_TYPE, + EcoreValidator.CONSISTENT_OPPOSITE_NOT_MATCHING -> + hint = + "Set the opposite of both references to each other; each must point to the class" + + " that declares the other"; + case EcoreValidator.CONSISTENT_OPPOSITE_BOTH_CONTAINMENT -> + hint = "Make only one of the two references a containment"; + case EcoreValidator.CONSISTENT_OPPOSITE_BAD_TRANSIENT -> + hint = "Make the opposite reference transient as well"; + case EcoreValidator.CONSISTENT_UNIQUE -> hint = "Set 'unique' to true"; + case EcoreValidator.CONSISTENT_TYPE_CLASS_REQUIRED -> + hint = "A reference must point to a class; use an attribute for data types"; + case EcoreValidator.CONSISTENT_TYPE_CLASS_NOT_PERMITTED -> + hint = "An attribute must have a data type; use a reference to point to a class"; + default -> { + // the message is all there is + } + } + } + return Optional.of(new Finding(element, message, hint)); + } + + /** EcoreValidator warns about names that differ only in case or '_'; EMF code clashes. */ + private static boolean isNameClash(Diagnostic diagnostic) { + return EcoreValidator.DIAGNOSTIC_SOURCE.equals(diagnostic.getSource()) + && (diagnostic.getCode() == EcoreValidator.UNIQUE_FEATURE_NAMES + || diagnostic.getCode() == EcoreValidator.UNIQUE_CLASSIFIER_NAMES + || diagnostic.getCode() == EcoreValidator.UNIQUE_ENUMERATOR_NAMES); + } + + /** + * The data of a name clash is the owner (class, package, or enum) followed by the clashing + * elements; features may be inherited from super types. + */ + private static Finding nameClash(int code, List elements) { + EObject owner = elements.get(0); + List clashing = + elements.subList(1, elements.size()).stream() + .filter(ENamedElement.class::isInstance) + .map(ENamedElement.class::cast) + .toList(); + // the last clashing element declared by the owner itself, else the owner + EObject located = + clashing.stream() + .filter(element -> element.eContainer() == owner) + .map(EObject.class::cast) + .reduce((first, second) -> second) + .orElse(owner); + String message = + String.format( + "the %s %s differ only in upper/lower case or '_', so their generated Java names" + + " clash", + clashKind(code), + String.join( + " and ", clashing.stream().map(element -> "'" + element.getName() + "'").toList())); + return new Finding( + located, + message, + code == EcoreValidator.UNIQUE_FEATURE_NAMES + ? "Rename one of them; features of the super types count as well" + : "Rename one of them"); + } + + private static String clashKind(int code) { + switch (code) { + case EcoreValidator.UNIQUE_FEATURE_NAMES: + return "features"; + case EcoreValidator.UNIQUE_ENUMERATOR_NAMES: + return "enum literals"; + default: + return "classifiers"; + } + } + + /** "The required feature 'eAttributeType' … must be set" repeats "must have a type". */ + private static boolean isMissingTypeOfTypedElement(Diagnostic diagnostic) { + return diagnostic.getData().contains(EcorePackage.Literals.EATTRIBUTE__EATTRIBUTE_TYPE) + || diagnostic.getData().contains(EcorePackage.Literals.EREFERENCE__EREFERENCE_TYPE); + } + + private static boolean isEcoreMetamodel(EObject object) { + return EcoreUtil.getRootContainer(object) == EcorePackage.eINSTANCE; + } +} diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/EcoreLocations.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/EcoreLocations.java index 0f94dde..d6781bf 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/EcoreLocations.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/EcoreLocations.java @@ -1,8 +1,11 @@ package tools.vitruv.methodologist.setup.vsum.service.metamodel; +import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.eclipse.emf.ecore.ENamedElement; +import org.eclipse.emf.ecore.EObject; import tools.vitruv.methodologist.setup.vsum.service.problem.Excerpts; /** @@ -37,4 +40,33 @@ public static Integer lineOf(String text, List namePath) { } return line; } + + /** + * Names from the root package down to the element. + * + * @param element an element of a metamodel + * @return e.g. {@code [model, Component, name]} + */ + public static List namePath(EObject element) { + List names = new ArrayList<>(); + for (EObject current = element; current != null; current = current.eContainer()) { + if (current instanceof ENamedElement named && named.getName() != null) { + names.add(0, named.getName()); + } + } + return names; + } + + /** + * Readable name of an element within its metamodel. + * + * @param element an element of a metamodel + * @return e.g. {@code Component.name}; the package name only for the root package + */ + public static String elementPath(EObject element) { + List names = namePath(element); + return names.size() > 1 + ? String.join(".", names.subList(1, names.size())) + : String.join(".", names); + } } diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/GeneratedMetamodel.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/GeneratedMetamodel.java index 3406e9e..997c398 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/GeneratedMetamodel.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/GeneratedMetamodel.java @@ -1,6 +1,7 @@ package tools.vitruv.methodologist.setup.vsum.service.metamodel; import java.util.List; +import org.eclipse.emf.ecore.EPackage; /** * A metamodel that was validated and placed into the generated project, together with its generated @@ -11,19 +12,40 @@ * @param ecoreFileName file name of the ecore inside the project's ecore directory * @param genmodelFileName file name of the genmodel inside the project's ecore directory * @param packages all packages EMF generates code for, including sub-packages + * @param ePackage the loaded root package, for checking the reactions against it; {@code null} if + * not available */ public record GeneratedMetamodel( String name, String nsUri, String ecoreFileName, String genmodelFileName, - List packages) { + List packages, + EPackage ePackage) { /** Makes the package list immutable. */ public GeneratedMetamodel { packages = List.copyOf(packages); } + /** + * Describes a metamodel without its loaded package. + * + * @param name name of the root EPackage + * @param nsUri namespace URI of the root EPackage + * @param ecoreFileName file name of the ecore inside the project's ecore directory + * @param genmodelFileName file name of the genmodel inside the project's ecore directory + * @param packages all packages EMF generates code for, including sub-packages + */ + public GeneratedMetamodel( + String name, + String nsUri, + String ecoreFileName, + String genmodelFileName, + List packages) { + this(name, nsUri, ecoreFileName, genmodelFileName, packages, null); + } + /** * A package for which EMF generates a {@code Package} interface. * diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/GeneratedNames.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/GeneratedNames.java new file mode 100644 index 0000000..8778b5c --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/GeneratedNames.java @@ -0,0 +1,129 @@ +package tools.vitruv.methodologist.setup.vsum.service.metamodel; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import org.eclipse.emf.codegen.ecore.genmodel.GenClassifier; +import org.eclipse.emf.codegen.ecore.genmodel.GenDataType; +import org.eclipse.emf.codegen.ecore.genmodel.GenEnum; +import org.eclipse.emf.codegen.ecore.genmodel.GenModel; +import org.eclipse.emf.codegen.ecore.genmodel.GenPackage; + +/** + * Finds class names that EMF generates Java code for, but that the Java compiler rejects. EMF + * escapes reserved words in feature, literal, and package names, but not in class names, and the + * generated package and factory interfaces share the namespace of the classes. + */ +final class GeneratedNames { + + // keywords and literals, plus the restricted identifiers that may not name a type + private static final Set RESERVED = + Set.of( + "abstract", + "assert", + "boolean", + "break", + "byte", + "case", + "catch", + "char", + "class", + "const", + "continue", + "default", + "do", + "double", + "else", + "enum", + "extends", + "final", + "finally", + "float", + "for", + "goto", + "if", + "implements", + "import", + "instanceof", + "int", + "interface", + "long", + "native", + "new", + "package", + "private", + "protected", + "public", + "return", + "short", + "static", + "strictfp", + "super", + "switch", + "synchronized", + "this", + "throw", + "throws", + "transient", + "try", + "void", + "volatile", + "while", + "true", + "false", + "null", + "_", + "var", + "yield", + "record", + "sealed", + "permits"); + + private GeneratedNames() {} + + /** + * Checks the class names of a metamodel against the Java code EMF generates for it. + * + * @param genModel the genmodel of the metamodel + * @return the problems found, located at the classifiers + */ + static List check(GenModel genModel) { + List findings = new ArrayList<>(); + for (GenPackage genPackage : genModel.getAllGenPackagesWithClassifiers()) { + Set generated = + Set.of(genPackage.getPackageInterfaceName(), genPackage.getFactoryInterfaceName()); + for (GenClassifier genClassifier : genPackage.getGenClassifiers()) { + if (genClassifier instanceof GenDataType && !(genClassifier instanceof GenEnum)) { + continue; // data types map to existing Java types + } + String name = genClassifier.getEcoreClassifier().getName(); + if (RESERVED.contains(name)) { + findings.add( + new EcoreDiagnostics.Finding( + genClassifier.getEcoreClassifier(), + String.format("'%s' is a reserved word in Java and cannot name a class", name), + String.format( + "Rename it, e.g. to '%s'; class names usually start with an upper-case" + + " letter", + capitalize(name)))); + } else if (generated.contains(name)) { + findings.add( + new EcoreDiagnostics.Finding( + genClassifier.getEcoreClassifier(), + String.format( + "the class '%s' has the name of the Java interface EMF generates for the" + + " package '%s'", + name, genPackage.getEcorePackage().getName()), + String.format( + "Rename the class; EMF generates %s and %s for the package", + genPackage.getPackageInterfaceName(), genPackage.getFactoryInterfaceName()))); + } + } + } + return findings; + } + + private static String capitalize(String name) { + return name.equals("_") ? "Unnamed" : Character.toUpperCase(name.charAt(0)) + name.substring(1); + } +} diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelProcessor.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelProcessor.java index 32f10ea..0397513 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelProcessor.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelProcessor.java @@ -20,7 +20,6 @@ import org.eclipse.emf.common.util.Diagnostic; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EClassifier; -import org.eclipse.emf.ecore.ENamedElement; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EStructuralFeature; @@ -103,6 +102,7 @@ public List process(List metamodels, Path proj for (EPackage ePackage : packages.values()) { genModels.put(ePackage, createGenModel(ePackage, resourceSet, ecoreDirectory)); } + checkGeneratedNames(packages, genModels); addUsedGenPackages(genModels); for (Resource resource : resourceSet.getResources()) { @@ -213,7 +213,7 @@ private void resolveCrossReferences( referencing, String.format( "%s references '%s', which is not part of the uploaded metamodels", - elementPath(referencing), proxyUri)) + EcoreLocations.elementPath(referencing), proxyUri)) .withHint( "Upload the metamodel '" + proxyUri.trimFragment().lastSegment() @@ -288,23 +288,35 @@ private void validate(Map packages) { private void collectErrors(Diagnostic diagnostic, UploadedFile file, List errors) { if (diagnostic.getChildren().isEmpty()) { - if (diagnostic.getSeverity() >= Diagnostic.ERROR) { - EObject element = - diagnostic.getData().stream() - .filter(EObject.class::isInstance) - .map(EObject.class::cast) - .findFirst() - .orElse(null); - errors.add( - element == null - ? BuildProblem.of(Source.METAMODEL, file.fileName(), diagnostic.getMessage()) - : locate(file, element, elementPath(element) + ": " + diagnostic.getMessage())); - } + EcoreDiagnostics.translate(diagnostic) + .ifPresent(finding -> errors.add(problem(file, finding))); return; } diagnostic.getChildren().forEach(child -> collectErrors(child, file, errors)); } + /** Rejects class names whose generated Java code does not compile. */ + private void checkGeneratedNames( + Map packages, Map genModels) { + List errors = new ArrayList<>(); + packages.forEach( + (file, ePackage) -> + GeneratedNames.check(genModels.get(ePackage)) + .forEach(finding -> errors.add(problem(file, finding)))); + throwIfAny(errors); + } + + private static BuildProblem problem(UploadedFile file, EcoreDiagnostics.Finding finding) { + BuildProblem problem = + finding.element() == null + ? BuildProblem.of(Source.METAMODEL, file.fileName(), finding.message()) + : locate( + file, + finding.element(), + EcoreLocations.elementPath(finding.element()) + ": " + finding.message()); + return problem.withHint(finding.hint()); + } + /** A problem of an element, located at its {@code name="..."} attribute in the upload. */ private static BuildProblem locate(UploadedFile file, EObject element, String message) { return locate(file.fileName(), file.text(), element, message); @@ -312,29 +324,11 @@ private static BuildProblem locate(UploadedFile file, EObject element, String me private static BuildProblem locate( String fileName, String text, EObject element, String message) { - Integer line = text == null ? null : EcoreLocations.lineOf(text, namePath(element)); + Integer line = + text == null ? null : EcoreLocations.lineOf(text, EcoreLocations.namePath(element)); return BuildProblem.at(Source.METAMODEL, fileName, text, line, null, message); } - /** Names from the root package down to the element, e.g. [model, Component, name]. */ - private static List namePath(EObject element) { - List names = new ArrayList<>(); - for (EObject current = element; current != null; current = current.eContainer()) { - if (current instanceof ENamedElement named && named.getName() != null) { - names.add(0, named.getName()); - } - } - return names; - } - - /** Readable name of an element, e.g. {@code Component.name}. */ - private static String elementPath(EObject element) { - List names = namePath(element); - return names.size() > 1 - ? String.join(".", names.subList(1, names.size())) - : String.join(".", names); - } - private static BuildProblem notValidEcore(UploadedFile metamodel, Exception e) { Throwable root = rootCause(e); if (root instanceof SAXParseException parseError && parseError.getLineNumber() > 0) { @@ -418,7 +412,8 @@ private GeneratedMetamodel describe(EPackage ePackage, GenModel genModel) { ePackage.getNsURI(), ePackage.eResource().getURI().lastSegment(), genModel.eResource().getURI().lastSegment(), - generatedPackages); + generatedPackages, + ePackage); } private static URI fileUri(Path path) { diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParser.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParser.java index 95e1d0f..ab70002 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParser.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/BuildOutputParser.java @@ -104,13 +104,10 @@ private static BuildProblem xtextProblem(Matcher xtext, ProjectSources sources) return BuildProblem.of(Source.REACTIONS, null, message); } SourceFile source = file.get(); + int uploadedLine = source.uploadedLine(line); return BuildProblem.at( - source.source(), - source.fileName(), - source.text(), - source.uploadedLine(line), - column, - message); + source.source(), source.fileName(), source.text(), uploadedLine, column, message) + .withHint(CompilerHints.forMessage(message, Excerpts.line(source.text(), uploadedLine))); } /** Lines following a javac error that belong to it, e.g. "symbol: ..." and "location: ...". */ diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/CompilerHints.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/CompilerHints.java new file mode 100644 index 0000000..662f995 --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/CompilerHints.java @@ -0,0 +1,220 @@ +package tools.vitruv.methodologist.setup.vsum.service.problem; + +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Explains what to change for the messages of the Reactions compiler (Xtext parser, Xbase type + * checker, and Reactions validator), whose wording assumes knowledge of the grammar. + */ +public final class CompilerHints { + + private record Rule(Pattern message, BiFunction hint) {} + + private static final Map TOKENS = + Map.of("RULE_ID", "a name", "RULE_STRING", "a quoted string", "RULE_INT", "a number"); + + private static final List RULES = + List.of( + rule( + "mismatched input '(.*)' expecting RULE_STRING", + (m, line) -> + line.strip().startsWith("import") + ? "A metamodel import needs the nsURI in quotes: import \"http://…\" as" + + " alias. Java imports such as 'import java.util.List' must come before" + + " the metamodel imports" + : "A quoted string is expected before '" + m.group(1) + "'"), + rule( + "mismatched input '(.*)' expecting (.*)", + (m, line) -> + String.format( + "'%s' is not allowed here, the parser expected %s; check the keywords and" + + " brackets just before it", + m.group(1), expected(m.group(2)))), + rule( + "extraneous input '(.*)' expecting (.*)", + (m, line) -> + String.format( + "Remove '%s', or check what comes before it; the parser expected %s", + m.group(1), expected(m.group(2)))), + rule( + "missing EOF at '(.*)'", + (m, line) -> + "Only reactions, routines, and further segments may follow a segment; check for" + + " an extra '}' before '" + + m.group(1) + + "'"), + rule( + "missing (.+) at '(.*)'", + (m, line) -> + String.format("Add %s before '%s'", expected(m.group(1)), m.group(2)) + + (m.group(1).equals("'}'") ? "; every '{' needs a matching '}'" : "")), + rule( + "no viable alternative at input '(.*)'", + (m, line) -> + "'" + + m.group(1) + + "' cannot be parsed here; compare it with the grammar, e.g. 'after element" + + " alias::Class inserted in alias::Container[feature]'"), + rule( + "Couldn't resolve reference to MetamodelImport '(.*)'\\.?", + (m, line) -> importAlias(m.group(1))), + rule( + "Couldn't resolve reference to EClassifier '(.*)'\\.?", + (m, line) -> metaclass(m.group(1))), + rule( + "Couldn't resolve reference to (?:EAttribute|EReference|EStructuralFeature)" + + " '(.*)'\\.?", + (m, line) -> feature(m.group(1))), + rule( + "Couldn't resolve reference to ReactionsSegment '(.*)'\\.?", + (m, line) -> + "Only reactions segments declared in the uploaded reactions can be imported or" + + " overridden; check the spelling of '" + + m.group(1) + + "'"), + rule( + "Couldn't resolve reference to JvmType '(.*)'\\.?", + (m, line) -> javaType(m.group(1))), + rule("(\\S+) cannot be resolved to a type\\.?", (m, line) -> javaType(m.group(1))), + rule("(\\S+) cannot be resolved\\.?", CompilerHints::unresolved), + rule( + "The method or field (\\S+) is undefined for the type (\\S+)", + (m, line) -> + String.format( + "'%s' has no feature or method '%s'; check the spelling against the" + + " metamodel, features are accessed by name, e.g. component.name", + m.group(2), m.group(1))), + rule( + "The method (\\S+)\\((.*)\\) is undefined for the type (\\S+)", + (m, line) -> + String.format( + "'%s' has no method '%s' for these arguments; check the spelling and the" + + " argument types", + m.group(3), m.group(1))), + rule( + "The method (\\S+)\\((.*)\\) is undefined", + (m, line) -> + String.format( + "There is no routine or method '%s' for these arguments; check the spelling" + + " and that the routine is declared in this reactions segment", + m.group(1))), + rule( + "Invalid number of arguments.*", + (m, line) -> "Pass exactly the parameters the routine or method declares"), + rule( + "Type mismatch: cannot convert from (.+) to (.+)", + (m, line) -> + String.format( + "The expression has the type %s where %s is needed; use a value of type %s" + + " or convert it", + m.group(1), m.group(2), m.group(2))), + rule( + "(?:Assignment to final (?:variable|field)|Cannot assign a value to final" + + " variable).*", + (m, line) -> + "Values declared with 'val' cannot be changed; declare it with 'var' instead"), + rule( + "Duplicate local variable (\\S+)", + (m, line) -> "Rename one of them; every 'val' and 'var' needs its own name"), + rule( + "Duplicate (reaction|routine) name: (.+)", + (m, line) -> + "Rename one of them; " + m.group(1) + " names must be unique in a segment"), + rule( + "Element cannot be (?:inserted into|removed from) single valued reference", + (m, line) -> "Use 'replaced at' for single-valued references"), + rule( + "Element of specified type cannot be contained in the specified features", + (m, line) -> "Use the type of the reference or one of its subclasses"), + rule( + "(?:Reactions segment|Routine|Element) names must not start with an underscore\\.?", + (m, line) -> "Rename it without the leading '_'")); + + private static final Pattern METACLASS_BEFORE = Pattern.compile("::\\s*\\^?$"); + private static final Pattern FEATURE_BEFORE = Pattern.compile("\\[\\s*\\^?$"); + + private CompilerHints() {} + + /** + * Returns a hint for a compiler message. + * + * @param message the compiler message, without location + * @param line the source line the message refers to, or {@code null} + * @return what to change, or {@code null} if the message is not known + */ + public static String forMessage(String message, String line) { + String trimmed = message.strip(); + String source = line == null ? "" : line; + for (Rule rule : RULES) { + Matcher matcher = rule.message().matcher(trimmed); + if (matcher.matches()) { + return rule.hint().apply(matcher, source); + } + } + return null; + } + + /** Xbase reports any unresolvable name alike; the text before it tells what it should be. */ + private static String unresolved(Matcher matcher, String line) { + String name = matcher.group(1); + int at = line.indexOf(name); + String before = at < 0 ? "" : line.substring(0, at); + if (METACLASS_BEFORE.matcher(before).find()) { + return metaclass(name); + } + if (FEATURE_BEFORE.matcher(before).find()) { + return feature(name); + } + if (line.matches(".*\\b" + Pattern.quote(name) + "\\s*::.*")) { + return importAlias(name); + } + return Character.isUpperCase(name.charAt(0)) + ? javaType(name) + : String.format( + "'%s' is not declared here; check the spelling and whether it is a parameter of the" + + " routine or a 'val' of its match or create block", + name); + } + + private static String metaclass(String name) { + return String.format( + "'%s' is not a class of the metamodel named before '::'; check the spelling and the" + + " alias", + name); + } + + private static String feature(String name) { + return String.format( + "Check the spelling of '%s'; 'after attribute' needs an attribute, 'after element' a" + + " reference, and 'replaced at' a single-valued one", + name); + } + + private static String importAlias(String name) { + return String.format( + "Import the metamodel at the top of the file: import \"\" as %s", name); + } + + private static String javaType(String name) { + return String.format( + "If '%s' is a Java type, import it at the top of the file, before the metamodel imports" + + " (e.g. 'import java.io.File'); a metamodel class is written as alias::%s", + name, name); + } + + private static String expected(String expected) { + String result = expected; + for (Map.Entry token : TOKENS.entrySet()) { + result = result.replace(token.getKey(), token.getValue()); + } + return result.replace("EOF", "the end of the file"); + } + + private static Rule rule(String message, BiFunction hint) { + return new Rule(Pattern.compile(message, Pattern.DOTALL), hint); + } +} diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/Excerpts.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/Excerpts.java index b3e62db..276fa92 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/Excerpts.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/problem/Excerpts.java @@ -34,6 +34,20 @@ public static String of(String text, Integer line, Integer column) { return content + "\n" + " ".repeat(offset) + "^"; } + /** + * Returns a line of the text. + * + * @param text the file content, may be {@code null} + * @param line 1-based line + * @return the line without its line break, or {@code null} if the text or line is unknown + */ + public static String line(String text, int line) { + if (text == null || line < 1) { + return null; + } + return text.lines().skip(line - 1L).findFirst().orElse(null); + } + /** * Returns the 1-based line containing the character at the offset. * diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsChecker.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsChecker.java new file mode 100644 index 0000000..97c3099 --- /dev/null +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsChecker.java @@ -0,0 +1,568 @@ +package tools.vitruv.methodologist.setup.vsum.service.reactions; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import org.eclipse.emf.ecore.EAttribute; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EEnum; +import org.eclipse.emf.ecore.ENamedElement; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import tools.vitruv.methodologist.setup.vsum.service.UploadedFile; +import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem; + +/** + * Checks the metamodel references of a Reactions file against the uploaded metamodels, the way the + * Reactions scope provider and validator resolve them: metamodel aliases, {@code alias::Class}, + * {@code alias::Class[feature]} in triggers, and the classes created in {@code create} blocks. + * + *

The check works on the text, so it reports only what is certainly wrong and leaves everything + * else (Xbase code in particular) to the Reactions compiler. It answers in milliseconds, before the + * Maven build, and suggests the intended name. + */ +final class ReactionsChecker { + + // Quantifiers are possessive: each repetition is followed by something it cannot consume, so + // backtracking would never find another match, and possessive matching cannot overflow the stack. + private static final String NAME = "\\^?[A-Za-z_]\\w*+"; + private static final String ID = "\\^?([A-Za-z_]\\w*+)"; + private static final String SEPARATOR = "\\s*+::\\s*+"; + private static final String QUALIFIED_NAME = NAME + "(?:\\s*+\\.\\s*+" + NAME + ")*+"; + private static final String REPLACED_AT = "replaced at"; + private static final String INSERTED_IN = "inserted in"; + private static final Pattern ALIAS = Pattern.compile(ID); + private static final Pattern METAMODEL_IMPORT = + Pattern.compile( + "\\bimport\\s++\"([^\"]*+)\"\\s++as\\s++" + + ID + + "(\\s++using\\s++qualified\\s++names)?+"); + private static final Pattern JAVA_IMPORT_NAME = + Pattern.compile( + "\\bimport\\s++(?:static\\s++(?:extension\\s++)?+)?+(?:" + + NAME + + "\\s*+\\.\\s*+)*+" + + ID); + private static final Pattern SEGMENT_METAMODELS = + Pattern.compile( + "\\b(?:in\\s++reaction\\s++to\\s++changes\\s++in|execute\\s++actions\\s++in)\\s++(" + + NAME + + "(?:\\s++and\\s++" + + NAME + + ")*+)"); + // a metaclass reference; the lookbehind skips qualified Java types like java.util.List::of + private static final Pattern METACLASS = + Pattern.compile("(? aliases = new LinkedHashMap<>(); + private final Set javaTypes = new HashSet<>(); + private final Collection allPackages; + private final List problems = new ArrayList<>(); + + private record Alias(String name, EPackage ePackage, boolean qualifiedNames) {} + + /** + * A trigger on a feature, e.g. {@code after element a::X inserted in a::Y[f]}. + * + * @param attributeChange whether it is an {@code after attribute} trigger + * @param elementAlias alias of the element type, or {@code null} if there is none + * @param elementName name of the element type, or {@code null} + * @param elementOffset offset of the element type name, or -1 + * @param change the change with single spaces, e.g. "inserted in" + * @param alias alias of the class holding the feature + * @param className name of the class holding the feature + * @param feature the feature name + * @param featureOffset offset of the feature name + */ + private record Trigger( + boolean attributeChange, + String elementAlias, + String elementName, + int elementOffset, + String change, + String alias, + String className, + String feature, + int featureOffset) {} + + private ReactionsChecker(UploadedFile file, Collection allPackages) { + this.file = file; + this.code = ReactionsProcessor.blankStrings(ReactionsProcessor.stripComments(file.text())); + this.allPackages = allPackages; + } + + /** + * Checks the metamodel references of a reactions file. + * + * @param file the uploaded reactions file + * @param packagesByNsUri all packages the reactions may import, including subpackages and Ecore + * @return the problems found; imports of unknown nsURIs are not reported here + */ + static List check(UploadedFile file, Map packagesByNsUri) { + ReactionsChecker checker = new ReactionsChecker(file, Set.copyOf(packagesByNsUri.values())); + checker.readImports(packagesByNsUri); + checker.checkSegmentMetamodels(); + checker.checkMetaclasses(); + checker.checkTriggers(); + checker.checkCreatedClasses(); + return grouped(checker.problems); + } + + /** Reports a repeated mistake, such as a misspelled alias, once with the other lines. */ + private static List grouped(List problems) { + Map> byMessage = new LinkedHashMap<>(); + problems.stream() + .sorted(Comparator.comparing(BuildProblem::line).thenComparing(BuildProblem::column)) + .forEach( + problem -> + byMessage + .computeIfAbsent(problem.message(), key -> new ArrayList<>()) + .add(problem)); + return byMessage.values().stream() + .map( + group -> { + BuildProblem first = group.get(0); + List otherLines = + group.stream() + .map(BuildProblem::line) + .filter(line -> !line.equals(first.line())) + .distinct() + .map(String::valueOf) + .toList(); + return otherLines.isEmpty() + ? first + : first.withMessage( + first.message() + " (also in lines " + String.join(", ", otherLines) + ")"); + }) + .toList(); + } + + private void readImports(Map packagesByNsUri) { + // string literals are blanked in the code, so imports are read from the text with comments + Matcher imports = METAMODEL_IMPORT.matcher(ReactionsProcessor.stripComments(file.text())); + while (imports.find()) { + aliases.put( + imports.group(2), + new Alias( + imports.group(2), packagesByNsUri.get(imports.group(1)), imports.group(3) != null)); + } + Matcher javaImports = JAVA_IMPORT_NAME.matcher(code); + while (javaImports.find()) { + javaTypes.add(javaImports.group(1)); + } + } + + private void checkSegmentMetamodels() { + Matcher lists = SEGMENT_METAMODELS.matcher(code); + while (lists.find()) { + Matcher names = ALIAS.matcher(lists.group(1)); + while (names.find()) { + String name = names.group(1); + if (!name.equals("and") && !aliases.containsKey(name)) { + unknownAlias(name, lists.start(1) + names.start(1)); + } + } + } + } + + private void checkMetaclasses() { + Matcher references = METACLASS.matcher(code); + while (references.find()) { + if (!isOverride(references.start())) { + checkMetaclass( + references.group(1), references.start(1), references.group(2), references.start(2)); + } + } + } + + private boolean isOverride(int offset) { + return OVERRIDE_BEFORE.matcher(code.substring(Math.max(0, offset - 200), offset)).find(); + } + + private void checkMetaclass(String aliasName, int aliasOffset, String name, int nameOffset) { + Alias alias = aliases.get(aliasName); + if (alias != null) { + resolve(alias, name, nameOffset); + } else if (Character.isLowerCase(aliasName.charAt(0)) && !javaTypes.contains(aliasName)) { + // 'Type::member' is static member access in Xbase; aliases are lower case by convention + unknownAlias(aliasName, aliasOffset); + } + } + + private void checkTriggers() { + Matcher starts = TRIGGER_START.matcher(code); + while (starts.find()) { + Trigger trigger = trigger(starts); + if (trigger != null) { + checkTrigger(trigger); + } + } + } + + /** Reads the trigger after {@code after element|attribute}, or {@code null} if it has none. */ + private Trigger trigger(Matcher start) { + Matcher element = TRIGGER_ELEMENT.matcher(code).region(start.end(), code.length()); + boolean typed = element.lookingAt(); + Matcher change = + TRIGGER_CHANGE.matcher(code).region(typed ? element.end() : start.end(), code.length()); + if (!change.lookingAt()) { + return null; + } + Matcher feature = TRIGGER_FEATURE.matcher(code).region(change.end(), code.length()); + if (!feature.lookingAt()) { + return null; + } + return new Trigger( + start.group(1).equals("attribute"), + typed ? element.group(1) : null, + typed ? element.group(2) : null, + typed ? element.start(2) : -1, + change.group(1).replaceAll("\\s++", " "), + feature.group(1), + feature.group(2), + feature.group(3), + feature.start(3)); + } + + private void checkTrigger(Trigger trigger) { + if (!(resolveQuietly(trigger.alias(), trigger.className()) instanceof EClass owner)) { + return; // unresolved classes are reported by checkMetaclasses + } + EStructuralFeature feature = owner.getEStructuralFeature(trigger.feature()); + if (feature == null) { + reportMissingFeature(trigger, owner); + } else if (trigger.attributeChange() != feature instanceof EAttribute) { + reportWrongFeatureKind(trigger, owner, feature); + } else if (feature instanceof EReference reference) { + checkElementChange(trigger, reference); + } + } + + private void reportMissingFeature(Trigger trigger, EClass owner) { + String kind = trigger.attributeChange() ? "attribute" : "reference"; + List candidates = + owner.getEAllStructuralFeatures().stream() + .filter(feature -> trigger.attributeChange() == feature instanceof EAttribute) + .map(ENamedElement::getName) + .toList(); + add( + trigger.featureOffset(), + String.format("'%s' has no %s '%s'", owner.getName(), kind, trigger.feature()), + suggestion(trigger.feature(), candidates, kind + "s")); + } + + private void reportWrongFeatureKind(Trigger trigger, EClass owner, EStructuralFeature feature) { + String name = owner.getName() + "." + trigger.feature(); + if (feature instanceof EReference) { + add( + trigger.featureOffset(), + String.format("'%s' is a reference, not an attribute", name), + String.format( + "Use 'after element %s %s[%s]'", + elementChangeFor(trigger.change(), feature), qualified(owner), trigger.feature())); + } else { + add( + trigger.featureOffset(), + String.format("'%s' is an attribute, not a reference", name), + String.format( + "Use 'after attribute %s %s[%s]'", + trigger.change(), qualified(owner), trigger.feature())); + } + } + + /** The element change that fits the multiplicity of a reference. */ + private static String elementChangeFor(String change, EStructuralFeature reference) { + if (!reference.isMany()) { + return REPLACED_AT; + } + return REPLACED_AT.equals(change) ? INSERTED_IN : change; + } + + private void checkElementChange(Trigger trigger, EReference reference) { + String name = reference.getEContainingClass().getName() + "." + reference.getName(); + boolean replaced = REPLACED_AT.equals(trigger.change()); + EClassifier elementType = resolveQuietly(trigger.elementAlias(), trigger.elementName()); + if (replaced && reference.isMany()) { + add( + trigger.featureOffset(), + String.format("'%s' is many-valued, so its elements are not replaced", name), + "Use 'inserted in' and 'removed from' for many-valued references"); + } else if (!replaced && !reference.isMany()) { + add( + trigger.featureOffset(), + String.format( + "'%s' is single-valued, so elements cannot be %s it", name, trigger.change()), + "Use 'replaced at' for single-valued references"); + } else if (elementType instanceof EClass elementClass + && reference.getEReferenceType() != null + && !related(elementClass, reference.getEReferenceType())) { + add( + trigger.elementOffset(), + String.format( + "elements of type '%s' cannot be contained in '%s', which holds '%s'", + elementClass.getName(), name, reference.getEReferenceType().getName()), + String.format( + "Use '%s' or one of its subclasses or super classes", + reference.getEReferenceType().getName())); + } + } + + private void checkCreatedClasses() { + Matcher creations = CREATE.matcher(code); + while (creations.find()) { + EClassifier classifier = resolveQuietly(creations.group(1), creations.group(2)); + int offset = creations.start(2); + if (classifier instanceof EEnum) { + add( + offset, + String.format("'%s' is an enum, so it cannot be created", classifier.getName()), + "Use one of its literals in the update block instead"); + } else if (classifier instanceof EClass eClass + && (eClass.isAbstract() || eClass.isInterface())) { + List concrete = + allClasses() + .filter(candidate -> !candidate.isAbstract() && !candidate.isInterface()) + .filter(candidate -> candidate.getEAllSuperTypes().contains(eClass)) + .map(EClass::getName) + .sorted() + .toList(); + add( + offset, + String.format( + "'%s' is %s, so it cannot be created", + eClass.getName(), eClass.isInterface() ? "an interface" : "abstract"), + concrete.isEmpty() + ? "Make the class non-abstract in the metamodel, or create a concrete subclass" + : "Create one of its concrete subclasses: " + String.join(", ", concrete)); + } + } + } + + /** Resolves {@code alias::Name} like the Reactions scope provider and reports failures. */ + private void resolve(Alias alias, String rawName, int offset) { + if (alias.ePackage() == null) { + return; // the import itself is reported + } + String name = rawName.replaceAll("[\\s^]", ""); + if (lookup(alias, name) == null) { + String reported = alias.qualifiedNames() ? name : name.split("\\.")[0]; + add( + offset, + String.format( + "'%s' is not a class of the metamodel '%s' (%s)", + reported, alias.name(), alias.ePackage().getNsURI()), + suggestion(reported, classifiers(alias).keySet(), "classes")); + } + } + + /** Resolves {@code alias::Name} without reporting; {@code null} if it does not resolve. */ + private EClassifier resolveQuietly(String aliasName, String rawName) { + Alias alias = aliasName == null ? null : aliases.get(aliasName); + return alias == null || alias.ePackage() == null + ? null + : lookup(alias, rawName.replaceAll("[\\s^]", "")); + } + + /** + * Looks up a name written after {@code alias::}. The name may run on into Xbase code, e.g. {@code + * alias::Class.literal}, so only the leading segments that name a classifier count. + */ + private static EClassifier lookup(Alias alias, String name) { + Map classifiers = classifiers(alias); + if (!alias.qualifiedNames()) { + return classifiers.get(name.split("\\.")[0]); + } + for (String candidate = name; + ; + candidate = candidate.substring(0, candidate.lastIndexOf('.'))) { + EClassifier classifier = classifiers.get(candidate); + if (classifier != null || candidate.indexOf('.') < 0) { + return classifier; + } + } + } + + /** Classes and enums visible through an import, keyed as they are written after {@code ::}. */ + private static Map classifiers(Alias alias) { + Map classifiers = new LinkedHashMap<>(); + collect( + alias.ePackage(), alias.qualifiedNames() ? qualifier(alias.ePackage()) : null, classifiers); + return classifiers; + } + + private static void collect(EPackage ePackage, String qualifier, Map into) { + for (EClassifier classifier : ePackage.getEClassifiers()) { + if (classifier instanceof EClass || classifier instanceof EEnum) { + into.putIfAbsent( + qualifier == null || qualifier.isEmpty() + ? classifier.getName() + : qualifier + "." + classifier.getName(), + classifier); + } + } + for (EPackage subpackage : ePackage.getESubpackages()) { + collect(subpackage, childQualifier(qualifier, subpackage), into); + } + } + + /** The qualifier of a subpackage's classifiers, or {@code null} without qualified names. */ + private static String childQualifier(String qualifier, EPackage subpackage) { + if (qualifier == null) { + return null; + } + return qualifier.isEmpty() ? subpackage.getName() : qualifier + "." + subpackage.getName(); + } + + /** Qualified names skip the root package, e.g. {@code sub.Class} for the root's subpackage. */ + private static String qualifier(EPackage ePackage) { + List names = new ArrayList<>(); + for (EPackage current = ePackage; + current.getESuperPackage() != null; + current = current.getESuperPackage()) { + names.add(0, current.getName()); + } + return String.join(".", names); + } + + private void unknownAlias(String name, int offset) { + add( + offset, + String.format("'%s' is not a metamodel imported in this file", name), + aliases.isEmpty() + ? String.format("Import it first: import \"\" as %s", name) + : suggestion(name, aliases.keySet(), "imported metamodels")); + } + + private Stream allClasses() { + return allPackages.stream() + .flatMap(ePackage -> ePackage.getEClassifiers().stream()) + .filter(EClass.class::isInstance) + .map(EClass.class::cast) + .distinct(); + } + + private static boolean related(EClass first, EClass second) { + return first == second + || first.eIsProxy() + || second.eIsProxy() + || first.getEAllSuperTypes().contains(second) + || second.getEAllSuperTypes().contains(first) + || isEObject(first) + || isEObject(second); + } + + private static boolean isEObject(EClass eClass) { + return "EObject".equals(eClass.getName()) + && eClass.getEPackage() != null + && "http://www.eclipse.org/emf/2002/Ecore".equals(eClass.getEPackage().getNsURI()); + } + + private String qualified(EClassifier classifier) { + return aliases.values().stream() + .filter(alias -> alias.ePackage() != null) + .filter(alias -> classifiers(alias).containsValue(classifier)) + .findFirst() + .map(alias -> alias.name() + "::" + classifier.getName()) + .orElse(classifier.getName()); + } + + /** + * Suggests the closest name, or lists the available ones. + * + * @param name the name as written + * @param candidates the names that would have been valid + * @param kind what the candidates are, e.g. "classes" + */ + static String suggestion(String name, Collection candidates, String kind) { + if (candidates.isEmpty()) { + return "There are no " + kind + " to choose from"; + } + String lower = name.toLowerCase(Locale.ROOT); + int best = + candidates.stream() + .filter(Objects::nonNull) + .mapToInt(candidate -> similarity(lower, candidate)) + .min() + .orElse(Integer.MAX_VALUE); + if (best <= Math.max(1, name.length() / 3)) { + List closest = + candidates.stream() + .filter(Objects::nonNull) + .filter(candidate -> similarity(lower, candidate) == best) + .distinct() + .limit(3) + .map(candidate -> "'" + candidate + "'") + .toList(); + return "Did you mean " + String.join(" or ", closest) + "?"; + } + return "Available " + + kind + + ": " + + String.join(", ", candidates.stream().limit(20).toList()) + + (candidates.size() > 20 ? ", …" : ""); + } + + /** Edit distance to the name or, for qualified names, to its last segment. */ + private static int similarity(String lowerName, String candidate) { + String lower = candidate.toLowerCase(Locale.ROOT); + return Math.min( + distance(lowerName, lower), + distance(lowerName, lower.substring(lower.lastIndexOf('.') + 1))); + } + + /** Levenshtein distance. */ + private static int distance(String a, String b) { + int[] previous = new int[b.length() + 1]; + int[] current = new int[b.length() + 1]; + for (int j = 0; j <= b.length(); j++) { + previous[j] = j; + } + for (int i = 1; i <= a.length(); i++) { + current[0] = i; + for (int j = 1; j <= b.length(); j++) { + int cost = a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1; + current[j] = + Math.min(Math.min(current[j - 1] + 1, previous[j] + 1), previous[j - 1] + cost); + } + int[] swap = previous; + previous = current; + current = swap; + } + return previous[b.length()]; + } + + private void add(int offset, String message, String hint) { + problems.add(ReactionsProcessor.problem(file, offset, message).withHint(hint)); + } +} diff --git a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsProcessor.java b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsProcessor.java index 10ed7d4..1e4b9d8 100644 --- a/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsProcessor.java +++ b/src/main/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsProcessor.java @@ -9,9 +9,12 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import lombok.extern.slf4j.Slf4j; +import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EcorePackage; import org.springframework.stereotype.Service; import tools.vitruv.methodologist.setup.vsum.service.UploadedFile; @@ -27,6 +30,7 @@ * Checks uploaded Reactions files against the uploaded metamodels, places them into the generated * project, and determines the change propagation specifications the Reactions compiler generates. */ +@Slf4j @Service public class ReactionsProcessor { @@ -64,6 +68,7 @@ public List process( metamodel -> metamodel.packages().forEach(pkg -> knownNsUris.add(pkg.nsUri()))); metamodels.forEach(metamodel -> knownNsUris.add(metamodel.nsUri())); knownNsUris.add(EcorePackage.eNS_URI); + Map packagesByNsUri = packagesByNsUri(metamodels); List problems = new ArrayList<>(); Map segmentOwners = new HashMap<>(); @@ -87,6 +92,8 @@ public List process( } } + problems.addAll(check(file, packagesByNsUri)); + List segments = segments(source); if (segments.isEmpty()) { problems.add( @@ -135,6 +142,37 @@ public List process( return specifications; } + /** + * Checks the metamodel references of a file. The check only reports what the Reactions compiler + * rejects as well, so if it fails itself, the compiler has the final say. + */ + private static List check(UploadedFile file, Map packages) { + try { + return ReactionsChecker.check(file, packages); + } catch (RuntimeException e) { + log.warn( + "Checking {} before the build failed; leaving it to the compiler", file.fileName(), e); + return List.of(); + } + } + + private static Map packagesByNsUri(List metamodels) { + Map packages = new HashMap<>(); + packages.put(EcorePackage.eNS_URI, EcorePackage.eINSTANCE); + metamodels.stream() + .map(GeneratedMetamodel::ePackage) + .filter(Objects::nonNull) + .forEach(ePackage -> register(ePackage, packages)); + return packages; + } + + private static void register(EPackage ePackage, Map packages) { + if (ePackage.getNsURI() != null) { + packages.putIfAbsent(ePackage.getNsURI(), ePackage); + } + ePackage.getESubpackages().forEach(subpackage -> register(subpackage, packages)); + } + /** * Moves Java imports ({@code import java.io.File}) in front of the metamodel imports ({@code * import "nsUri" as alias}). The Reactions grammar only accepts them in that order, but the @@ -228,7 +266,7 @@ public static List segments(String source) { public record Segment(String name, int offset) {} /** Replaces string literals by spaces of the same length, keeping offsets and line breaks. */ - private static String blankStrings(String source) { + static String blankStrings(String source) { Matcher matcher = STRINGS.matcher(source); StringBuilder result = new StringBuilder(); while (matcher.find()) { @@ -239,7 +277,7 @@ private static String blankStrings(String source) { return result.toString(); } - private static BuildProblem problem(UploadedFile file, int offset, String message) { + static BuildProblem problem(UploadedFile file, int offset, String message) { String text = file.text(); return BuildProblem.at( Source.REACTIONS, diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceTest.java index 0adff97..92bff89 100644 --- a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceTest.java +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/VsumProjectBuildServiceTest.java @@ -7,6 +7,8 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static tools.vitruv.methodologist.setup.vsum.service.TestFiles.fixture; import static tools.vitruv.methodologist.setup.vsum.service.TestFiles.text; @@ -177,9 +179,44 @@ void leavesOutVitruvOclWithoutConstraints() throws IOException { assertFalse(main.contains("import tools.vitruv.dsls.vitruvocl"), main); } + /** A misspelled class is reported with a suggestion before the Maven build starts. */ + @Test + void rejectsMisspelledClassesBeforeTheMavenBuild() { + MavenBuildRunner mavenBuildRunner = mock(MavenBuildRunner.class); + VsumProjectBuildService checked = + new VsumProjectBuildService( + new MetamodelProcessor(), + new ReactionsProcessor(), + new ConstraintsProcessor(), + new NeoJoinViewDefinitionProcessor(), + new ProjectGenerator(properties), + mavenBuildRunner, + properties); + String reactions = + fixture("templateReactions.reactions") + .text() + .replace("val entity = new model2::Entity", "val entity = new model2::Entitiy"); + VsumBuildRequest request = + new VsumBuildRequest( + List.of(fixture("model.ecore"), fixture("model2.ecore")), + List.of(text("my.reactions", reactions)), + List.of(), + List.of()); + + VsumBuildException exception = + assertThrows(VsumBuildException.class, () -> checked.buildProjectJar(request)); + + verify(mavenBuildRunner, never()).build(any(), any()); + assertEquals(VsumErrorCodes.REACTIONS_ERROR, exception.getErrorCode()); + BuildProblem problem = exception.getProblems().get(0); + assertEquals("my.reactions", problem.file()); + assertEquals(lineContaining(reactions, "model2::Entitiy"), problem.line()); + assertEquals("Did you mean 'Entity'?", problem.hint()); + } + /** - * A typo in a class name is reported at its line in the upload, as one problem. Runs the real - * Maven build. + * An error only the Reactions compiler finds, a misspelled feature in Xbase code, is reported at + * its line in the upload, as one problem with a hint. Runs the real Maven build. */ @Test @EnabledIfSystemProperty(named = "vsum.integration", matches = "true") @@ -187,7 +224,8 @@ void reportsReactionsErrorsAtTheirLineInTheUpload() { String reactions = fixture("templateReactions.reactions") .text() - .replace("val entity = new model2::Entity", "val entity = new model2::Entitiy"); + .replaceFirst("entity\\.name = component\\.name", "entity.nme = component.name"); + VsumBuildException exception = assertThrows( VsumBuildException.class, @@ -204,10 +242,10 @@ void reportsReactionsErrorsAtTheirLineInTheUpload() { BuildProblem problem = exception.getProblems().get(0); assertEquals(Source.REACTIONS, problem.source()); assertEquals("my.reactions", problem.file()); - assertEquals( - lineContaining(reactions, "model2::Entitiy"), problem.line(), exception.getMessage()); - assertTrue(problem.message().contains("Entitiy"), problem.message()); - assertTrue(problem.excerpt().contains("new model2::Entitiy"), problem.excerpt()); + assertEquals(lineContaining(reactions, "entity.nme"), problem.line(), exception.getMessage()); + assertTrue(problem.message().contains("nme"), problem.message()); + assertTrue(problem.excerpt().contains("entity.nme"), problem.excerpt()); + assertTrue(problem.hint() != null && problem.hint().contains("nme"), exception.getMessage()); } /** diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelChecksTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelChecksTest.java new file mode 100644 index 0000000..21a5a17 --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/metamodel/MetamodelChecksTest.java @@ -0,0 +1,183 @@ +package tools.vitruv.methodologist.setup.vsum.service.metamodel; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static tools.vitruv.methodologist.setup.vsum.service.TestFiles.text; + +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import tools.vitruv.methodologist.setup.vsum.service.UploadedFile; +import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem; +import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; + +/** + * Metamodels that EcoreValidator accepts, or reports confusingly, but whose generated Java code + * does not compile. Each case was confirmed with a real build of the generated project. + */ +class MetamodelChecksTest { + + private static final String STRING = + "eType=\"ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString\""; + + private final MetamodelProcessor processor = new MetamodelProcessor(); + + @TempDir Path projectRoot; + + @Test + void rejectsFeaturesThatDifferOnlyInCaseAlsoWhenInherited() { + List problems = + problems( + """ + + + + + + + """ + .formatted(STRING)); + + assertEquals(1, problems.size()); + BuildProblem problem = problems.get(0); + assertEquals( + "Derived.X: the features 'x' and 'X' differ only in upper/lower case or '_', so their" + + " generated Java names clash", + problem.message()); + assertEquals(10, problem.line()); + assertEquals("Rename one of them; features of the super types count as well", problem.hint()); + } + + @Test + void rejectsClassesAndLiteralsThatDifferOnlyInCase() { + List problems = + problems( + """ + + + + + + + """); + + assertEquals( + List.of( + "entity: the classifiers 'Entity' and 'entity' differ only in upper/lower case or '_'," + + " so their generated Java names clash", + "Kind.a: the enum literals 'A' and 'a' differ only in upper/lower case or '_', so" + + " their generated Java names clash"), + problems.stream().map(BuildProblem::message).toList()); + } + + @Test + void rejectsReservedJavaWordsAsClassNames() { + List problems = + problems( + """ + + + + + + """ + .formatted(STRING)); + + assertEquals( + List.of( + "class: 'class' is a reserved word in Java and cannot name a class", + "record: 'record' is a reserved word in Java and cannot name a class"), + problems.stream().map(BuildProblem::message).toList()); + assertEquals( + "Rename it, e.g. to 'Class'; class names usually start with an upper-case letter", + problems.get(0).hint()); + assertEquals(6, problems.get(0).line()); + } + + @Test + void rejectsClassesNamedLikeTheGeneratedPackageInterfaces() { + List problems = + problems( + """ + + + """); + + assertEquals(2, problems.size()); + assertEquals( + "ProbePackage: the class 'ProbePackage' has the name of the Java interface EMF generates" + + " for the package 'probe'", + problems.get(0).message()); + assertEquals( + "Rename the class; EMF generates ProbePackage and ProbeFactory for the package", + problems.get(0).hint()); + } + + @Test + void explainsUntypedFeaturesWithoutObjectDumps() { + List problems = + problems( + """ + + + + + """); + + assertEquals( + List.of( + "Thing.untyped: The typed element must have a type", + "Custom: the data type has no instance type name"), + problems.stream().map(BuildProblem::message).toList()); + assertEquals( + "Set the type, e.g. EString for an attribute or a class of the metamodels for a" + + " reference", + problems.get(0).hint()); + problems.forEach(problem -> assertFalse(problem.message().contains("org.eclipse"))); + } + + @Test + void acceptsNamesThatEmfEscapes() { + List uploads = + List.of( + ecore( + """ + + + + + + + + + + + """ + .formatted(STRING))); + + assertDoesNotThrow(() -> processor.process(uploads, projectRoot)); + } + + private List problems(String classifiers) { + List uploads = List.of(ecore(classifiers)); + return assertThrows(VsumBuildException.class, () -> processor.process(uploads, projectRoot)) + .getProblems(); + } + + private static UploadedFile ecore(String classifiers) { + return text( + "probe.ecore", + """ + + + %s + """ + .formatted(classifiers.indent(2))); + } +} diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/problem/CompilerHintsTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/problem/CompilerHintsTest.java new file mode 100644 index 0000000..9f0c68b --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/problem/CompilerHintsTest.java @@ -0,0 +1,74 @@ +package tools.vitruv.methodologist.setup.vsum.service.problem; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +class CompilerHintsTest { + + @Test + void explainsTheOrderOfImports() { + assertTrue( + CompilerHints.forMessage( + "mismatched input 'java' expecting RULE_STRING", "import java.io.File") + .startsWith("A metamodel import needs the nsURI in quotes")); + } + + @Test + void translatesGrammarTokens() { + assertEquals( + "Remove '{', or check what comes before it; the parser expected 'after'", + CompilerHints.forMessage( + "extraneous input '{' expecting 'after'", "reaction ComponentRenamed {{")); + assertEquals( + "'+' is not allowed here, the parser expected a name; check the keywords and brackets" + + " just before it", + CompilerHints.forMessage("mismatched input '+' expecting RULE_ID", "routine +x()")); + assertEquals( + "Add '}' before 'routine'; every '{' needs a matching '}'", + CompilerHints.forMessage("missing '}' at 'routine'", "routine x() {")); + } + + @Test + void tellsWhatAnUnresolvedNameShouldBeFromItsPosition() { + assertTrue( + CompilerHints.forMessage( + "Entitiy cannot be resolved.", " val entity = new model2::Entitiy") + .startsWith("'Entitiy' is not a class of the metamodel named before '::'")); + assertTrue( + CompilerHints.forMessage( + "nam cannot be resolved.", "after attribute replaced at model::Component[nam]") + .startsWith("Check the spelling of 'nam'; 'after attribute' needs an attribute")); + assertEquals( + "Import the metamodel at the top of the file: import \"\" as cad", + CompilerHints.forMessage("cad cannot be resolved.", "after element cad::Part created")); + assertTrue( + CompilerHints.forMessage("File cannot be resolved.", "new File(\"x\")") + .startsWith("If 'File' is a Java type, import it")); + assertTrue( + CompilerHints.forMessage("entitiy cannot be resolved.", "entitiy.name = component.name") + .startsWith("'entitiy' is not declared here")); + } + + @Test + void explainsXbaseAndValidatorMessages() { + assertEquals( + "Values declared with 'val' cannot be changed; declare it with 'var' instead", + CompilerHints.forMessage("Assignment to final variable", "weight += comp.weight")); + assertEquals( + "Use 'replaced at' for single-valued references", + CompilerHints.forMessage("Element cannot be inserted into single valued reference", "")); + assertTrue( + CompilerHints.forMessage( + "The method createAndRegisterRot(System) is undefined", + "call createAndRegisterRot(x)") + .startsWith("There is no routine or method 'createAndRegisterRot'")); + } + + @Test + void hasNoHintForUnknownMessages() { + assertNull(CompilerHints.forMessage("Something entirely new", "x")); + } +} diff --git a/src/test/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsCheckerTest.java b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsCheckerTest.java new file mode 100644 index 0000000..9922ea9 --- /dev/null +++ b/src/test/java/tools/vitruv/methodologist/setup/vsum/service/reactions/ReactionsCheckerTest.java @@ -0,0 +1,296 @@ +package tools.vitruv.methodologist.setup.vsum.service.reactions; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static tools.vitruv.methodologist.setup.vsum.service.TestFiles.fixture; +import static tools.vitruv.methodologist.setup.vsum.service.TestFiles.text; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import tools.vitruv.methodologist.setup.vsum.service.UploadedFile; +import tools.vitruv.methodologist.setup.vsum.service.metamodel.GeneratedMetamodel; +import tools.vitruv.methodologist.setup.vsum.service.metamodel.MetamodelProcessor; +import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem; +import tools.vitruv.methodologist.setup.vsum.service.problem.BuildProblem.Source; +import tools.vitruv.methodologist.setup.vsum.service.problem.VsumBuildException; + +/** The checks of reactions against the loaded sample metamodels, before any Maven build. */ +class ReactionsCheckerTest { + + private static final String HEADER = + """ + import "http://vitruv.tools/methodologisttemplate/model" as model + import "http://vitruv.tools/methodologisttemplate/model2" as model2 + + reactions: modelToModel2 + in reaction to changes in model + execute actions in model2 + """; + + private final ReactionsProcessor processor = new ReactionsProcessor(); + + @TempDir Path projectRoot; + + private List metamodels; + + @BeforeEach + void loadMetamodels() throws IOException { + metamodels = + new MetamodelProcessor() + .process(List.of(fixture("model.ecore"), fixture("model2.ecore")), projectRoot); + } + + @Test + void acceptsTheTemplateReactions() { + List reactions = List.of(fixture("templateReactions.reactions")); + + assertDoesNotThrow(() -> processor.process(reactions, metamodels, projectRoot)); + } + + @Test + void suggestsTheClassForAMisspelledClass() { + BuildProblem problem = + single( + HEADER + + """ + routine create(model::Component component) { + create { + val entity = new model2::Entitiy + } + } + """); + + assertEquals(Source.REACTIONS, problem.source()); + assertEquals(9, problem.line()); + assertEquals(30, problem.column()); + assertEquals( + "'Entitiy' is not a class of the metamodel 'model2'" + + " (http://vitruv.tools/methodologisttemplate/model2)", + problem.message()); + assertEquals("Did you mean 'Entity'?", problem.hint()); + assertEquals( + " val entity = new model2::Entitiy\n ^", problem.excerpt()); + } + + @Test + void listsTheClassesIfNoneIsClose() { + BuildProblem problem = + single(HEADER + "reaction X {\n after element model::Banana created\n call {}\n}\n"); + + assertEquals( + "Available classes: Component, Link, Protocol, Device, Server, System, Router", + problem.hint()); + } + + @Test + void reportsAMisspelledAliasOnceWithTheOtherLines() { + BuildProblem problem = + single( + HEADER + + """ + routine a(modl::System system) { + match { + require absence of modl::Component corresponding to system + } + } + """); + + assertEquals(7, problem.line()); + assertEquals( + "'modl' is not a metamodel imported in this file (also in lines 9)", problem.message()); + assertEquals("Did you mean 'model'?", problem.hint()); + } + + @Test + void checksTheMetamodelsOfTheSegment() { + BuildProblem problem = + single(HEADER.replace("execute actions in model2", "execute actions in model3")); + + assertEquals(6, problem.line()); + assertEquals(20, problem.column()); + assertEquals("'model3' is not a metamodel imported in this file", problem.message()); + assertEquals("Did you mean 'model' or 'model2'?", problem.hint()); + } + + @Test + void suggestsTheFeatureOfTheRightKind() { + BuildProblem problem = + single( + HEADER + + "reaction X {\n" + + " after element model::Component inserted in model::System[component]\n" + + " call {}\n}\n"); + + assertEquals(8, problem.line()); + assertEquals("'System' has no reference 'component'", problem.message()); + assertEquals("Did you mean 'components'?", problem.hint()); + } + + @Test + void tellsToUseElementChangesForReferences() { + BuildProblem problem = + single( + HEADER + + "reaction X {\n after attribute replaced at model::System[components]\n" + + " call {}\n}\n"); + + assertEquals("'System.components' is a reference, not an attribute", problem.message()); + assertEquals("Use 'after element inserted in model::System[components]'", problem.hint()); + } + + @Test + void tellsToUseAttributeChangesForAttributes() { + BuildProblem problem = + single( + HEADER + + "reaction X {\n after element replaced at model::Component[name]\n" + + " call {}\n}\n"); + + assertEquals("'Component.name' is an attribute, not a reference", problem.message()); + assertEquals("Use 'after attribute replaced at model::Component[name]'", problem.hint()); + } + + @Test + void checksTheMultiplicityOfTheChangedReference() { + BuildProblem replaced = + single( + HEADER + + "reaction X {\n after element replaced at model::System[components]\n" + + " call {}\n}\n"); + BuildProblem inserted = + single( + HEADER + + "reaction X {\n after element inserted in model::Link[protocol]\n" + + " call {}\n}\n"); + + assertEquals( + "'System.components' is many-valued, so its elements are not replaced", replaced.message()); + assertEquals( + "'Link.protocol' is single-valued, so elements cannot be inserted in it", + inserted.message()); + assertEquals("Use 'replaced at' for single-valued references", inserted.hint()); + } + + @Test + void checksThatTheElementFitsTheReference() { + BuildProblem problem = + single( + HEADER + + "reaction X {\n" + + " after element model::Protocol inserted in model::System[components]\n" + + " call {}\n}\n"); + + assertEquals(8, problem.line()); + assertEquals(24, problem.column()); + assertEquals( + "elements of type 'Protocol' cannot be contained in 'System.components', which holds" + + " 'Component'", + problem.message()); + } + + @Test + void rejectsCreatingAbstractClassesAndNamesTheConcreteOnes() { + BuildProblem problem = + single( + "import \"http://www.eclipse.org/emf/2002/Ecore\" as ecore\n" + + HEADER.replace("execute actions in model2", "execute actions in ecore") + + "routine r() {\n create {\n val c = new ecore::EClassifier\n }\n}\n"); + + assertEquals("'EClassifier' is abstract, so it cannot be created", problem.message()); + assertEquals("Create one of its concrete subclasses: EClass, EDataType, EEnum", problem.hint()); + } + + @Test + void leavesXbaseCodeOverridesStringsAndCommentsAlone() { + UploadedFile reactions = + text( + "valid.reactions", + "import org.eclipse.emf.ecore.util.EcoreUtil\n" + + HEADER + + """ + import routines other using qualified names + // model::Commented + reaction other::Overridden { + after element model::Component deleted + call { + EcoreUtil::delete(affectedEObject) + val text = "model::InAString" + java.util.Collections::emptyList() + } + } + routine other.nested::name(model::Component component) { + update { component.name = '''model2::Rich''' } + } + reactions: other + in reaction to changes in model and model2 + execute actions in model2 + """); + + List uploads = List.of(reactions); + + assertDoesNotThrow(() -> processor.process(uploads, metamodels, projectRoot)); + } + + @Test + void resolvesQualifiedNamesOfSubpackages() throws IOException { + List nested = + new MetamodelProcessor() + .process( + List.of( + text( + "outer.ecore", + """ + + + + + + + + """)), + projectRoot.resolve("nested")); + UploadedFile reactions = + text( + "qualified.reactions", + """ + import "http://example.org/outer" as q using qualified names + import "http://example.org/outer" as s + reactions: names + in reaction to changes in q + execute actions in s + reaction A { after element q::inner.Deep created call {} } + reaction B { after element s::Deep created call {} } + reaction C { after element q::Top created call {} } + reaction D { after element q::Deep created call {} } + """); + + List uploads = List.of(reactions); + + VsumBuildException exception = + assertThrows( + VsumBuildException.class, () -> processor.process(uploads, nested, projectRoot)); + + assertEquals(1, exception.getProblems().size()); + BuildProblem problem = exception.getProblems().get(0); + assertEquals(9, problem.line()); + assertEquals("Did you mean 'inner.Deep'?", problem.hint()); + } + + private BuildProblem single(String reactions) { + List uploads = List.of(text("checked.reactions", reactions)); + VsumBuildException exception = + assertThrows( + VsumBuildException.class, () -> processor.process(uploads, metamodels, projectRoot)); + assertEquals(1, exception.getProblems().size(), exception.getMessage()); + return exception.getProblems().get(0); + } +}