问题
Here is a snapshot of my grammar:
Sort:
name=ID
;
Variable
name=ID ':' type=[Sort]
My requirement is to have a predefined Sort let's call it Loc. There is no need for the user to define this sort, thus when a Variable is defined with a Loc type, Xtext should automatically reference it to my predefined Sort. How can I initiate the program so that at the beginning a Sort instance is generated? I already used the Factory method 'CreateSort' in my validator class, but no use. any idea?
回答1:
Your intuition with createSort Factory method is good but you have to call it at the right time. The Loc instance must be created before linking step. To do so, you have to bind a custom Linker and override it.
public class CustomLinker extends LazyLinker {
@Override
protected void beforeModelLinked(EObject model,
IDiagnosticConsumer diagnosticsConsumer) {
super.beforeModelLinked(model, diagnosticsConsumer);
if (model instanceof Root) {
Root root = (Root) model;
Sort locSort = MyDslFactory.eINSTANCE.createSort();
locSort.setName("Loc");
root.getContent().add(locSort);
}
}
}
Then, you bind this custom linker class in Runtime Module:
public class MyDslRuntimeModule extends org.xtext.example.mydsl.AbstractMyDslRuntimeModule {
@Override
public Class<? extends ILinker> bindILinker() {
return CustomLinker.class;
}
}
Now you can write a file containing
variable : Loc
The reference will be resolved.
来源:https://stackoverflow.com/questions/25738815/add-eobject-to-the-parse-tree-programaticaly