XText w / XBase - 初始化生成的变量

时间:2014-03-06 12:03:51

标签: dsl xtext xtend

我正在使用带有XBase语法的Xtext 在每个生成的java类中,我需要在模型inferer中初始化类变量。这个变量没有在我的模型中定义,但没有区别 我已经可以通过函数

生成这个变量了
element.toField("isSomethingSet", newTypeRef("boolean"))

,但我无法初始化它。我确定我应该使用带有初始化程序的附加参数的 toField 函数,但因为它的类型为 Procedure1 我不知道如何用它。

这是我从Xtext文档中略微更改的示例。 语法:

grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.xbase.Xbase
generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"
Domainmodel:
  (elements += AbstractElement)*; 
AbstractElement:
   Entity;
Entity:
  'entity' name = ID ('extends' superType = JvmTypeReference)?
  '{'
    (features += Feature)*
  '}';
Feature:
  name = ID ':' type = JvmTypeReference;

ModelInferrer.xtend

import com.google.inject.Inject
import org.eclipse.xtext.naming.IQualifiedNameProvider
import org.eclipse.xtext.xbase.jvmmodel.AbstractModelInferrer
import org.eclipse.xtext.xbase.jvmmodel.IJvmDeclaredTypeAcceptor
import org.eclipse.xtext.xbase.jvmmodel.JvmTypesBuilder
import org.xtext.example.mydsl.myDsl.Entity

class MyDslJvmModelInferrer extends AbstractModelInferrer {

    @Inject extension JvmTypesBuilder

    @Inject extension IQualifiedNameProvider

    def dispatch void infer(Entity element, IJvmDeclaredTypeAcceptor acceptor,
        boolean isPrelinkingPhase) {
        acceptor.accept(element.toClass(element.fullyQualifiedName)).initializeLater     [
            documentation = element.documentation
            members += element.toField("isSomethingSet", newTypeRef("boolean"))
            for (feature : element.features) {
                members += feature.toField(feature.name, feature.type)
                members += feature.toSetter(feature.name, feature.type)
                members += feature.toGetter(feature.name, feature.type)
            }
        ]
    }
}

1 个答案:

答案 0 :(得分:5)

该过程封装了配置字段所需的代码,例如:设置可见性,静态标志,文档或字段初始值设定项:

element.toField("isSomethingSet", newTypeRef("boolean")) [
  initializer = '''false''' // with Xtext 2.5 or
  initializer = [ append('false') ] // prior to 2.5
]