Building a compiler for your own language: model-to-model transformations

Building a compiler for your own language_ model-to-model transformations

Most of the work done in tools supporting a language consists in manipulating the AST. In this post we are going to see how to perform transformation and processing on the Abstract Syntax Tree through model-to-model transformations. These techniques will be useful to perform operation like:

  • validation: finding errors in the AST
  • remove syntax sugar: by transforming the AST into equivalent but more explicit forms
  • fill symbol tables and resolve symbols

All these techniques will be based on generic ways to navigate and change the AST. Let’s see how.

This post is the part of a series. The goal of the series is to describe how to create a useful language and all the supporting tools.

  1. Building a lexer
  2. Building a parser
  3. Creating an editor with syntax highlighting
  4. Build an editor with autocompletion
  5. Mapping the parse tree to the abstract syntax tree
  6. Model to model transformations
  7. Validation
  8. Generating bytecode

After writing this series of posts I refined my method, expanded it, and clarified into this book titled
How to create pragmatic, lightweight languages

 

Code

Code is available on GitHub under the tag 06_transformations

The operations we need

We will need to:

  • process the AST: we want to do some operation to extract information from the AST
  • transform the AST: we want to transform the single nodes of the AST

Implement the transformations manually

We could implement the transformation manually on each single class of the AST. For example, this is how we could implement these methods on a SumExpression

We would have just to repeat it for each single class of our metamodel. Quite boring, eh?

Transformations using reflection

The alternative is to use reflection. In this way we can specify these operations for Node and they will work for every class of every metamodel (so basically, for every language we are going to work on).

Testing the transformations

It all looks nice and well but the question is: does it actually work?
Let’s try.

In this little test we will transform references to a variable into references to a variable B.

Conclusions

Another building block for the future. In the next steps we will see how to use this, for example to implement validation.

Download the guide with 68 resources on Creating Programming Languages

68resources

Receive the guide to your inbox to read it on all your devices when you have time

Powered by ConvertKit
1 reply

Comments are closed.