Let’s try to be a compiler first

Compiler is a mechanism that takes a piece of code and turn it into something else. Let’s compile simple DBN code into a physical drawing.

There are 3 commands in this DBN code, “Paper” defines color of the paper, “Pen” defines color of the pen, and “Line” draw a line. 100 in color parameter means 100% black or rgb(0%, 0%, 0%) in CSS. The image produced in DBN are always in grayscale. In DBN, a paper is always 100×100, line-width is always 1, and Line is defined by x y coordinates of starting point and ending point counting from bottom-left corner.

Let’s try to be a compiler ourself. Stop here, grab a paper and a pen and try compiling following code as drawing.

Paper 0

Pen 100

Line 0 50 100 50

Did you draw a black line in the middle from left side to right side? Congratulations! You just became a compiler.

Compiled result

How does a compiler work ?

Let’s look at what just happened in our head as a compiler.

1. Lexical Analysis (tokenization)

First thing we did was to separate each keywords (called tokens) by white space. While we are separating words, we also assigned primitive types to each tokens, like “word” or “number”.

lexical analysis

2. Parsing (Syntactical Analysis)

Once a blob of text is separated into tokens, we went through each of them and tried to find a relationship between tokens.

In this case, we group together numbers associated with command keyword. By doing this, we start seeing a structure of the code.

Parsing

3. Transformation

Once we analyzed syntax by parsing, we transformed the structure to something suitable for the final result. In this case, we are going to draw an image, so we are going to transform it to step by step instruction for humans.

Transformation

4. Code Generation

Lastly, we make a compiled result, a drawing. At this point, we just follow the instructions we made in previous step to draw.

Code Generation

And that’s what a compiler does!

The drawing we made is the compiled result (like .exe file when you compile C code). We can pass this drawing to anyone or any device (scanner, camera etc) to “run it” and everyone (or device) will see a black line in the middle.