In this tutorial, we will create a mini programming language that compiles:
to
which we will use to draw interesting stuff on the HTML <canvas>
.
Contents
Basic stuff
Before doing the code, we need to know the logic.
Lexing
First, we lex the code. This is the process of splitting the code into tokens and removing unnecessary characters.
Validating
Then, we validate the code by checking if the tokens are valid.
Compiling
Then, we compile the code to JavaScript.
Programming part
We will name our mini-language drawlang
. Its syntax looks like this:
center
, left
, top
, right
, bottom
, color
are keywords. ,
is also a keyword that draws. - Any color like
red
, blue
, green
, black
, white
, etc., is a color. - Any number is a number.
Setting the basic stuff
First, I’ll create an index.js
file and add this code.
We import the fs
module to read the file.
Creating the lexer
I’ll create a function named tokenize
that accepts a string as an argument.
Now, keep variables to store the tokens and keep track of the current position.
And a utility function to add a token to the tokens array.
Now, we can start tokenizing the code. We will use a while loop to iterate over the code.
Then we get the current character.
We will use a switch statement to determine the type of the token.
We ignore all the whitespace characters.
If it’s a comma, we add a COMMA
token.
Else, we check if it’s a number or a keyword.
And we finally escape the while loop and return the tokens.
Now try adding this code and running node index.js
and see the output.
Nice! We have created the lexer/tokenizer.
Validating and compiling to JavaScript
We will create a function named compile
that accepts an array of tokens as an argument.
Then add some variables to store the compiled code and keep track of the current position.
Again, we use a while loop to iterate over the tokens.
This time we create a function to get the current token.
And a function named expect
to check if the next token is the expected one and if not, throw an error.
After that, we use a switch statement to determine the type of the token.
If it’s a COMMA
, we add _draw()
to the compiled code.
Else, we check if it’s a NAME
token.
At last, we finally escape the while loop and return the compiled code.
Now try adding this code and running node index.js
and see the output.
If you did it right, you should see the following output:
We’ll write the code in a file named out.js
so you can run it in the browser.
Nice! We now create a framework.js
file that will contain the code for the framework.
In the HTML
file, we’ll add the canvas and the script tag.
And if you open the HTML file, you will see the following output.
Conclusion
Thank you for reading the tutorial. The complete code is on GitHub.