Skip to content

August 14, 2012


Writing Xtext Scope Providers with Xtend


Scope is an important concept in the design of programming languages. In Xtext, scoping is used to drive two major parts of your DSL: linking and content assist. While Xtext applies the 80/20 rule very successfully, thereby providing you with a decent scoping implementation out of the box, eventually you’ll have to roll up your sleeves and write your own scope provider.

Over the years, implementing scope providers has become significantly easier, much thanks to the tiny internal scoping DSL provided by org.eclipse.xtext.scoping.Scopes (src). However, collecting the elements that make up a scope can be a very cumbersome task if you have to use Java. Let’s face it – Java has not been built for traversing models.

A language much better suited to traversing models is Xtend, the newest kid on the X block. If you didn’t yet give it a try, you should do so now – even if you’re not writing an Xtext DSL. Xtend directly translates to Java code and allows you to write very concise code by eliminating much of Java’s ceremony. You can use it to write everything you’d write in Java – from Android UIs to web applications – so why not write Eclipse plug-ins with Xtend?

To write the scope provider for your language using Xtend, you need to follow a few very simple steps:

  1. Disable generating the scope provider stub. Open Generate<YourDSL>.mwe2 in the DSL project and find the line

    fragment = scoping.ImportNamespacesScopingFragment { }
  2. Change this line to

    fragment = scoping.ImportNamespacesScopingFragment {
        generateStub = false
  3. If you already have a Java-based scope provider, copy the implementation to a safe place and delete the Java file to make room for the new Xtend-based scope provider.

  4. Create a new Xtend class <YourDSLPackage>.<YourDSL>ScopeProvider.xtend in the DSL project. Make sure this class inherits from org.eclipse.xtext.scoping.impl.AbstractDeclarativeScopeProvider.

  5. Start writing your scope provider using Xtend.

  6. Don’t forget to smile :-)

Thanks for reading this post. Follow me on twitter here to be notified about updates and other posts I write. Or, subscribe to my RSS feed here. If you want to get in touch with me, use the contact form.

Fork me on GitHub
Read more from DSLs, Xtext