Add eObject to the parse tree programaticaly

烂漫一生 提交于 2019-12-11 22:23:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!