简体   繁体   English

Xtext:从MyDsl引用Java类

[英]Xtext: Reference a Java class from MyDsl

In my DSL, I want to have a code that looks like: 在我的DSL中,我想要一个类似如下的代码:

SomeType varName;

Where SomeType is a Java class. 其中SomeType是Java类。

Later on, if lets say SomeType is an enum java-class, and someone writes 后来,如果让我们说SomeType是一个枚举Java类,有人写了

varName=SOME_VALUE

I want to do a validation to see if SomeType.java actually has SOME_VALUE as a value in its enum. 我想进行验证以查看SomeType.java是否在其枚举中实际上具有SOME_VALUE作为值。 I saw this tutorial https://eclipse.org/Xtext/documentation/305_xbase.html 我看到了本教程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). 但是我不确定这是我所需要的(我需要导入.mydsl文件,而不仅仅是jvm)。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks. 谢谢。

If you want references to Java types, use org.eclipse.xtext.xbase.Xtype as super-grammar. 如果要引用Java类型,请使用org.eclipse.xtext.xbase.Xtype作为超级语法。 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 如果您还想表达分配,我建议使用org.eclipse.xtext.xbase.Xbase作为超级语法(继承自Xtype),并在要引用Java元素的地方使用XExpression规则,例如

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). 为了简化操作,您还可以将XExpression用于变量声明(XVariableDeclaration是特殊的XExpression)和分配(对于XAssignment是另一种特殊的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): 只需调用XBlockExpression(一个用大括号括起来的复合表达式):

MyFunkyRule:
    ...
    expressionBlock=XBlockExpression
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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