Eclipse Xtext Generator

This is one of a sequence of pages that I have written about Xtext which start here. Once we have setup the '.xtext' file to define the grammar (as described on this page) we can now go on to define how to generate code from our language. To do that we configure files in the generator directory as follows.


The generation of code is done by a file written in the xtend language. This is a language similar to java which compiles to java. This language has capabilities that help with generating text such as a sort of formatted text (Templates) which is put between triple single quotes '''. These templates implement the interface: java.lang.CharSequence.

Here is a code snippet which shows the general form of the code generator.
class EditorGenerator implements IGenerator {

	override void doGenerate(Resource resource, IFileSystemAccess fsa) {
        compile(resource.contents.head as Model))

	def className(Resource res) {
		var name = res.URI.lastSegment
		return name.substring(0, name.indexOf('.'))

	def compile(Model model) ''' 
        «IF model.eContainer != null»
            package «model.eResource.className»;
        «ENDIF»«IF model.c != null» «compile(model.c)» «ENDIF»
        «IF model.p != null» «compile(model.p)» «ENDIF»
        «IF model.d != null» «compile(model.d)» «ENDIF»

    /* CategoryDef */
    def compile(CategoryDef f) '''
      public interface «f.longname» «IF f.cp != null»
This then gets compiled to java source. So the compile(Model model) class would get compiled to something like this:
public CharSequence compile(final Model model) {
  StringConcatenation _builder = new StringConcatenation(); {
    EObject _eContainer = model.eContainer();
    boolean _notEquals = (!Objects.equal(_eContainer, null));
    if (_notEquals) {
      _builder.append("package ");
      Resource _eResource = model.eResource();
      String _className = this.className(_eResource);
      _builder.append(_className, "");


Further Reading

We go on to look at how code is generated for xbase on this page.

metadata block
see also:


Correspondence about this page

This site may have errors. Don't use for critical systems.

Copyright (c) 1998-2023 Martin John Baker - All rights reserved - privacy policy.