Monday, May 10, 2010

MPS is simple

If you have ever seen or tried MPS and it didn’t make a lot of sense, do not believe your first impression, because meta-programming in MPS is simple.

There are only two things you have to know to create something useful in MPS:

  • editors and
  • generators.

Editors

Editors is the way you interact with your language in MPS. The thing is that MPS doesn’t edit text files. It works with abstract syntax tree. When you edit a program in MPS, you edit AST. Here is AST for hello world program written in Java:

To define a language you describe types of nodes that can be in your language AST. In MPS this is done with concepts (they are green).

In a way concepts are classes for AST nodes and AST nodes are instances of concepts.

For each concept you define an editor.

Editors allow you to edit and view AST nodes in a text-like form. In a way editors that you define for concepts are “editor classes” and the area in which you actually edit programs consists of “editor instances”.

If you like MVC pattern and its flavours, you can think about AST nodes as a model and editors as view and controller. You can read more about concepts here and here and about editors here.

Generators

While having AST and being able to edit it is great, usually you would like to produce something useful like java code or text files. This is what generators are for. They take AST and transform it into real files on your hard drive.

Generators can transform AST directly into real files:

…or they can transform AST into another AST. This is useful when you want to build your language on top of another language. For example, in MPS there a bundled language called base language which is basically Java extended with features like closures. You can create generator to translate your language into base language and generator from base language will automatically transform it into java files:

This way you have a chain of AST transformations and don’t have to deal with file generation.

You can read more about generators here. There are also quite good generator demos.

What’s next?

There are a lot of other interesting things in MPS like type system, IDE support and much more, but to do something useful you don’t have to know anything except editors and generators. In my view, the best way to get started is to go through MPS tutorial and generator demos. Do not just read them and look at screenshots, install MPS and try to repeat all the steps. Be aware, that tutorials are not too easy and might cover too many topics to understand at once. Don’t get frustrated if something is not clear. After tutorials you might read parts of user guide or try doing something simple yourself. It doesn’t take a lot of time, but it’s rewarding and it’s the best way to understand what MPS is good for.

0 comments: