Tuesday, November 01, 2011

Build Your Own JVM Language!

Xtext has already simplified development of domain-specific languages a lot. From a simple grammar definition you not only get a full language infrastructure but also powerful Eclipse-based tool support.
Now it's getting even better.

Today we release Xtext 2.1, which comes with surprisingly easy to use support for defining little languages targeting the JVM (Java Virtual Machine). You only need to define two files:
  • the grammar
  • a mapping to Java concepts
The first one is not new. It's still the same concise and readable grammar language we always had in Xtext.

The second script is the big deal: it allows you to map your language concepts to any number of Java types, fields and methods. By doing that you implicitly tell the framework what it needs to know to provide you with a fully working IDE including an incremental compiler!

We have written a nice little tutorial explaining the five steps needed to get a language like the following:

import java.util.List

package my.model {

    entity Person {
        name: String
        firstName: String
        friends: List<Person>
        address : Address

        op getFullName() : String {
            return firstName + " " + name;
        }
        
        op getFriendsSortedByFullName() : List<Person> {
            return friends.sortBy( f | f.fullName);
        }
    }
    
    entity Address {
        street: String
        zip: String
        city: String
    }
}

As you can see, it supports all kinds of advanced features such as Java generics and full expressions even including closures. But you not only get a working parser, linker and compiler but a fully-working high-end Eclipse plug-in on top! The screencast demos the resulting language and IDE and briefly shows how that can be built. Be creative and have fun!