javaenumsreferencextextxbase

Xtext: Reference a Java class from MyDsl


In my DSL, I want to have a code that looks like:

SomeType varName;

Where SomeType is a Java class.

Later on, if lets say SomeType is an enum java-class, and someone writes

varName=SOME_VALUE

I want to do a validation to see if SomeType.java actually has SOME_VALUE as a value in its enum. I saw this tutorial https://eclipse.org/Xtext/documentation/305_xbase.html

but I'm not sure this is what I need (I need to import .mydsl files, not only jvm). Any help would be appreciated. Thanks.


Solution

  • If you want references to Java types, use org.eclipse.xtext.xbase.Xtype as super-grammar. Then you can write a rule like

    VariableDeclaration:
        type=JvmTypeReference name=ValidID ';';
    

    to express your code sample.

    If you also want to express assignments, I suggest to use org.eclipse.xtext.xbase.Xbase as super-grammar (which inherits from Xtype) and use the XExpression rule wherever you want to reference elements from Java, e.g.

    VariableAssignment:
        variable=[VariableDeclaration|ValidId] '=' expression=XExpression;
    

    To make things easier, you could also use XExpression for variable declarations (XVariableDeclaration is a special XExpression) and for assignments (XAssignment is another special XExpression). That would allow to write stuff like

    {
        var SomeType varName
        varName = SomeType.SOME_VALUE
    }
    

    with a single call to XBlockExpression (a composite expression surrounded by curly braces):

    MyFunkyRule:
        ...
        expressionBlock=XBlockExpression
        ...