Thursday, April 11, 2013

Multiple Validators in Xtext

Early validation of domain specific languages (DSLs) and suggestions on how to fix these errors ('quickfixes') are key for a good end user experience and for avoiding problems in the toolchain, for instance in generators that use DSL models: The more editor validations, the better. This description shows how to improve the maintainability and modularity of validation code for Xtext DSLs by simply splitting them. In the generated [MyDsl]JavaValidator, an annotation referring to other custom validators has to be added as shown below:
@ComposedChecks(validators =
{MyCustomValidator.class, MyOthercustomValidator.class})
public class MyDslJavaValidator extends AbstractMyDslJavaValidator {

// check method as usual inside the generated Java Validator
public void checkMyDslElement(MyEntity myEntity) { // ...
Please note that the custom validator has to override the register()-method. Apart from that, the checks look exactly as they would if they were in the generated validator.
// Example for a split custom validator written in Xtend
public class MyCustomValidator extends AbstractDeclarativeValidator {

override register(EValidatorRegistrar registrar) {
//not needed for classes used as ComposedCheck

// additional check method in separate validator
def void checkMyDslElement(MyEntity myEntity) {
[...] // validation code