Search code examples
xtext

Validate number of function parameters in XText


I have in my DSL a prototype:

prototype function SaySomething(String Words);
prototype function SayHelloLanguage(String Language, String Words);

I want to validate that when you call one of those function prototypes

SaySomething("Hello World!");
SayHelloLanguage("French", "Bonjour World!");

That you include the correct number and type of parameters.

Prototype:
   'prototype function' name=ID '('parameters+=Parameter (',' parameters+=Parameter)* ')'
Function:
    name=[Prototype] '('parameters+=Parameter (',' parameters+=Parameter)* ')'
                        ^^^^^ how do I cross reference/validate this part                       

I figured out cross-referencing and scoping enough so that it will auto-complete the function name, but I don't see how in the grammar you can define a correct parameter count or type restriction.

Do I need to implement a validator? or is this something I can define in the grammar?


Solution

  • I finally figured this out.

    Within the DSLJavaValidator.java you add a check:

    @check
    public void checkParameterCount(Function function){
        Prototype p = (Prototype) function.eCrossReferences().get(0);
        if(function.getParameters.size() != p.getParameters.size()){
           error("Bad Parameter Count", DSLPackage.Literals.FUNCTION__NAME);
        }
    }
    

    All of the functions annotated with @check get called as you type in the editor.