Enhancing the Refactoring in your Xtext-DSL

Enhancing the Refactoring in your Xtext-DSL

Some time ago I wanted to enhace the experience developers would get when developing with a DSL I’m working at with things like better refactoring in Eclipse.

A lot of things that you would want to have are already provided out of the box, these things might include the Rename Refactoring.

The Rename Refactoring is working as you expect it, this means that if you want to rename a variable in Java, all occurrences are updated in the correct context (may it be the method or class).

However, there are more things that could be nice to have if you rename elements.

If you rename a class in Java or Xtend, the file which contains the class gets renamed too, which makes a lot of sense if you think of your DSL-file as having one named root element (like a class).

The renaming of files however isn’t part of the default Renaming Strategy generated by Xtext, so here we can do our enhancement!

As I said before, Xtend itself has this behaviour in it’s Refactoring via Eclipse so I was lurking around their GithubGithub-Repository to find out where I might want to start and found the XtendRenameStrategy.java class.

After trying around with their source and adapting it to my DSL it was pretty straight forward.

Given the following root element in a grammar:

RootElement:
    'class' name=ID '{' otherElements+=OtherElements* '}'

We could alter their code to look like that:

The only thing that changes for other DSLs would be the file extension (line 6) and the name of the root element (line 39).

After writing that Rename Strategy you will have to register it to be used within the IDE. You can do this in your „MyDslUiModule.java“ and need to create a method to override the binding of the IRenameStrategy:

@Override
public Class<? extends IRenameStrategy> bindIRenameStrategy()
{
    return MyDslRenameStrategy.class;
}

You might get compiler warnings about API restrictions, but as Christian Dietrich has said here it’s just to let you know that the API might change.

api restriction simply says: you are not allowed to complain if the api changes. besides this have a look at the xtend code is the right thing to do

Thats it for my „Enhancing the Refactoring in your Xtext-DSL“ post. Do you have any cool enhancements to the refactoring in Xtext/Eclipse that everyone should know? If so, feel free to share it!

comments powered by Disqus