Search code examples
xtext

Check if entered text is valid in Xtext


lets say we have some grammar like this.

Model:
    greeting+=Greeting*;

Greeting:
    'Hello' name=ID '!';

I would like to check whether the text written text in name is a valid text. All the valid words are saved in an array. Also the array should be filled with words from a given file.

So is it possible to check this at runtime and maybe also use this words as suggestions.

Thanks


Solution

  • For this purpose you can use a validator.
    A simple video tutorial about it can be found here

    In your case the function in the validator could look like this:

    public static val INVALID_NAME = "greeting_InvalidName"
    
    @Check
    def nameIsValid(Greeting grt) {
        val name = grt.getName() //or just grt.Name
        val validNames = NewArrayList
        //add all valid names to this list
    
        if (!validNames.contains(name)) {
            val errorMsg = "Name is not valid"
            error(errorMsg, GreetingsPackage.eINSTANCE.Greeting_name, INVALID_NAME)
        }
    }
    

    You might have to replace the "GreetingsPackage" if your DSL isn't named Greetings.
    The static String passed to the error-method serves for identification of the error. This gets important when you want to implement Quickfixes which is the second thing you have asked for as they provide the possibility to give the programmer a few ideas how to actually fix this particular problem.
    Because I don't have any experience with implementing quickfixes myself I can just give you this as a reference.