Skip to content

A complete Front End compiler

Introduction

Some time ago I started to take a deep dive into the topics related to the interpreters, compilers and programming languages in general. To learn more I borrowed a book from a university library (Compilers, Principles, Techniques & Tools, second edition) and found out an interesting piece of code. The “Appendix A” at the end of the book has a complete front end compiler written in Java. As I am more familiar with C# I created the C# version inspired by the one written in Java and refactored it a little so that it is a bit more readable (I hope I did not crash the implementation logic… the unit test is green for now :D).

Frontend and backend compilers

This front end compiler takes a source code and translates to an intermediate representation of the code in the form of three-address intermediate code. The intermediate representation can be further an input to the backend compiler (i haven’t created my own yet, maybe some day…). The backend compiler optimizes and generates code for a target platform.

Example

Based on an example from the book the front end compiler can translate a high level source code (language syntax is based on the grammar defined in the book) to the three-address intermediate code:

Source code:
{
	int i; int j; float v; float x; float[100] a;
	while(true)
	{
		do i = i+1; while(a[i] < v);
		do j = j-1; while(a[j] > v);
		if(i>=j) break;
		x = a[i];
		a[i] = a[j];
		a[j] = x;
	}
}

Output:
L1:
L3:
   i = i + 1
L5:
   t1 = i * 8
   t2 = a [t1]
   if t2 < v goto L3
L4:
   j = j - 1
L7:
   t3 = j * 8
   t4 = a [t3]
   if t4 > v goto L4
L6:
   if false i >= j goto L8
L9:
   goto L2
L8:
   t5 = i * 8
   x = a [t5]
L10:
   t6 = i * 8
   t7 = j * 8
   t8 = a [t7]
   a [t6] = t8
L11:
   t9 = j * 8
   a [t9] = x
   goto L1
L2:

Summary

In my opinion the compiler related topics are great as you can learn the internals of the programming languages you use on a daily basis. The topic itself is not that easy and it took me some time to figure out how the aforementioned compiler works – even though it looks like the the most basic one…

If you are interested in the code itself or just want to write some simple unit tests for the given language you can do so! You can find the compiler implementation on my GitHub and the test project.

Have a nice day, bye!

Published in.NETCompilers

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *