简体   繁体   中英

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.

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, eg

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
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM