This article is an introduction to Transpilers which is the process of translating one programming language into another. This process may be called compiling, transpiling, or interpreting depending on the nature of the input and output languages. Usually compiling is used to describe the process of translating a higher level language, like Java, into machine language, and traspiling is used to describe the process of translating one higher level language into another higher level language. In this article I will show you how to translate, or “transpile”, one high level language into another high level language. Translating one language into another seems like a daunting task at first, but when you break it up into smaller, more manageable tasks, you will realize it is not so hard.

Table of Contents
Constants
Tokenizer
Parser
Code Generator

Our goal in this article is to understand how to make a program that will transpile a made-up language called “Minilisp” into JavaScript. Minilisp is just a very simple version of Lisp, which is a high level programming language famous for its use of parenthesis.

Here’s an example of Minilisp. The code below will give us the answer to the simple math proble 3 + 4 * 2:

(+ 3 (* 4 2))

1
2
3

(+ 3 (* 4 2))

Our transpiler will take this code and translate it into a JavaScript program that does the exact same thing:

add(3, multiply(4, 2));

1
2
3

add(3, multiply(4, 2));

We will also go a little bit beyond this to allow our Minilisp user to compose basic functions into higher level functions. An example of this is combining addition and division to make function that returns the average of two numbers. That would look like this in Minilisp:

(defn average
(x, y)
(/ (+ x y) 2 ))

1
2
3
4
5

(defn average
(x, y)
(/ (+ x y) 2 ))

The code above uses the “defn” function call which takes three parameters. The first parameter is the name of the function, which in this case is “average”. The second parameter to defn defines what kind of parameters the function we are defining will accept, and the third parameter is the code that will be executed when we call our new “average” function. If we read over this code in English it would be something like “I am invoking defn to define a new function called average that takes two parameters x and y and returns the value obtained by adding x and y and then diving the result by two.”

Now that we are familiar with Minilisp, lets start working on our Minilisp transpiler. The first step is to take the process of transpiling Minilisp in Javascript and break it into smaller chunks each of which performs just one step in the overall process. Below is a diagram that shows you how we are going to break up this task. We start with a block of text that contains our Minilisp code and then that code gets passed through a series of intermediate steps before it comes out as functional JavaScript.